Lazy-load is a way to prevent images from loading before scroll. There are many plugins that help you with this, some themes even have a built-in lazy-load function.

Here I will show you that it’s not hard to implement it yourself.

Step 1: Replace SRC Attribute

When an image has src attribute, it will always load no matter what. So our first step is to temporarily prefix them with data-.

In WordPress, we can filter the images html and replace img src attribute using str_replace() PHP function, add the following code in your theme functions.php.

/**
 * Lazy Load All Images
 * 
 * To Exclude, simply add this attr to img html: loading="not_lazy"
 *
 * @param string $html          Post thumbnail HTML
 * 
 * @return string Filtered post image HTML.
 */
add_filter( 'post_thumbnail_html', 'atdev_add_lazy_load_to_imgs', 10, 1 );
add_filter( 'wp_get_attachment_image', 'atdev_add_lazy_load_to_imgs', 10, 1 );
function atdev_add_lazy_load_to_imgs( $html ) {

	if( ! is_admin() && ! str_contains(strtolower($html), 'loading="not_lazy"') ){

		$html = str_replace(
			' src=', // Find
			' loading="lazy" data-lazy src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkqAcAAIUAgUW0RjgAAAAASUVORK5CYII=" data-src=', // Replace
			$html // String
		);

	}
	return $html;
}

Step 2: Load in Intersect using JS

The intersection observer API helps to identify DOM elements that are in the viewport. It’s the way of implementing lazy load without writing event handler functions.

Add the following JS code in your theme footer.php.

<script>
/**
 * Lazy Load Images using Intersection Observer
 * 
 */
var observer = new IntersectionObserver(onIntersect);
document.querySelectorAll("[data-lazy]").forEach((img) => {
	observer.observe(img);
});

function onIntersect(entries) {
	entries.forEach((entry) => {
		if (entry.target.getAttribute("loading") == 'not_lazy' || entry.target.getAttribute("data-processed") || !entry.isIntersecting)
			return true;
		entry.target.setAttribute("src", entry.target.getAttribute("data-src"));
		entry.target.setAttribute("data-processed", true);
	});
}
</script>

You may not want to lazy load above the fold images, use the following JS code:

<script>
/**
 * (Trying to) Not lazy load above the fold images
 */
document.addEventListener('DOMContentLoaded',() => {
	
	win_height = window.innerHeight;
	imgs = document.getElementsByTagName('img');
	for (var i = 0; i < imgs.length; i++) {
		// At least 20 px above the fold
		if( imgs[i].getAttribute("loading") != 'not_lazy' && (imgs[i].offsetTop+20) < win_height ){
			imgs[i].setAttribute("src", imgs[i].getAttribute("data-src"));
			imgs[i].setAttribute("data-processed", true);
		} 
	}

});
</script>

Note: Make sure <img /> must have height and width attribute.

Conclusion:

Lazy-load has become a necessity in all blogs and corporate websites. You don’t have to worry about SEO because Google themselves has confirmed that they can detect lazy-load.

It’s a best practice of SEO, which leads to lowering your web page load time by optimizing your overall site. This approach includes several benefits like-

  • Your site visitors won’t require using much bandwidth to view your web pages.
  • You can boost your website’s search rankings.
  • It leads to an uplift of users and keeps them engaged, which ultimately leads to higher sales and conversions.
  • The site will be able to offer a better mobile experience.
  • Boost site performance by providing high-resolution images.

What do you think of lazy loading? Have you used it to improve the performance of your website? Let me know, in the comment section below.

Have fun coding!

Categorized in:

WordPress,

Tagged in:

,