leepeterson
10/4/2016 - 6:37 PM

An example of my "Progressive Lazy Load" technique in WordPress using vanilla Javascript

An example of my "Progressive Lazy Load" technique in WordPress using vanilla Javascript

#hero,
#placeholder-overlay {
	background-size: cover;
	background-position: center;
}

#hero {
	position: relative;
	min-height: 500px;
	overflow: hidden;
}

#placeholder-overlay {
	position: absolute;
	/* Negative margins to retain sharp edges */
	top: -10px;
	bottom: -10px;
	left: -10px;
	right: -10px;
	/* Blur out pixelated image */
	filter:blur(10px);
	opacity: 1;
	transition: opacity 1s linear;
}
#placeholder-overlay.fade-out {
	/* Fade out with a class */
	opacity: 0;
}
// Cache elements
var hero = document.getElementById('hero'),
	placeholderOverlay = document.getElementById('placeholder-overlay');

// Check if the elements exist
if ( masthead && placeholderOverlay ) {
	// Create an image with the full size URL
	var img = new Image();
	img.src = masthead.dataset.imageSrc;
	
	// When it finishes loading, add it to our hero and fade out the overlay
	img.onload = function () {
		placeholderOverlay.classList.add('fade-out');
		masthead.style.backgroundImage = "url(" + img.src + ")";
	};
}
<?php while (have_posts()) : the_post(); ?>
	<?php 
	// Get the placeholder image and full size image URLs
	if ( has_post_thumbnail() ) {
		$image_id = get_post_thumbnail_id();

		$full_size_image = wp_get_attachment_image_src( $image_id,'full', true);
		$full_size_image_url = $full_size_image[0];

		$placeholder_image = wp_get_attachment_image_src( $image_id,'thumbnail', true);
		$placeholder_image_url = $placeholder_image[0];
	} else {
		// You may want a fallback in case there is no image
	}
	?>

	<?php // Give the hero section a data attribute with the full size URL ?>
	<div id="hero" data-image-src="<?php echo $full_size_image_url; ?>">

		<?php // Insert the low quality placeholder ?>
		<span id="placeholder-overlay" style="background-image: url(<?php echo $placeholder_image_url; ?>);"></span>

		<?php // Load more content here if you like ?>
		
	</div>
<?php endwhile; ?>