A lot of WordPress sites want to stop the lazy loading of images, but doing so is not as easy as many people think, or rather a common solution does not always take care of the issue. In this short tutorial I’ll describe the problem and provide two full solutions that work.
The Problem with Lazy Loading Images
WordPress 5.5 added lazy load all images by default because it was thought that doing so would improve page loading times and provide a small performance boost. Chrome and some other browsers announced the intention to lazy load images by default also. However, the law of unintended consequences kicked in and it was discovered that lazy loading images above the fold, or on the initially visible screen, resulted in a performance hit in relation to the Largest Contentful Paint (LCP), or the point at which the user perceives the page as being usable / visible. In WordPress 5.9 the default of lazy loading all images was modified so that the first image, typically the site logo, would not be lazy loaded.
Note that WordPress isn’t actually holding the image back or delaying sending images to the web browser. What happens is that an attribute is added to the HTML image tag:
loading="lazy"
The web browser then delays loading the image. The loading attribute has two options, “lazy” or “eager” and “eager” is the same as having no attribute, though it overrides the browser if it lazy loads by default.
The “Common” Incomplete Solution
If you don’t want to lazy load images, well, no problem. WordPress provided a hook and with a simple code snippet for disabling the default lazy loading of images. To load the snippet you could use a snippet plugin, like WPCodeBox, or add the PHP snippet to a child theme.
add_filter('wp_lazy_loading_enabled', '__return_false');
When you add the snippet instead of the image attribute saying “lazy” it says “eager.” The problem is that the snippet doesn’t work in all cases! Many themes use a WordPress function to retrieve the featured image:
the_post_thumbnail()
This method is used to get the featured image and when it does the image is fetched as an attachment, loading is set to “lazy,” and the “eager” override in the filter isn’t set. Kadence is one of the themes which uses this function to get the featured image.
The Solution
I did some Googling on the issue and noticed that Jeff Starr has a plugin Disable Lazy Load. This is the code in the plugin:
add_filter( 'wp_lazy_loading_enabled', '__return_false' );
function disable_lazy_load_featured_images($attr, $attachment = null) {
$attr['loading'] = 'eager';
return $attr;
}
add_filter('wp_get_attachment_image_attributes', 'disable_lazy_load_featured_images');
I tried it and it worked completely. If you prefer adding a snippet you can use this code, or if you prefer a plugin then you can use Jeff’s plugin.