Exclude a specific number of images from lazy loading by targeting an attribute

Google PageSpeed recommends that anything resting above the fold shouldn't be lazyloaded. This can be done using our images and iframe exclusions box by targeting specific image names and classes.

A potential performance issue might arise when using sliders, carousels, or grids positioned above the fold. That kind of structure will have two kinds of repetitive images:

  • Visible images that shouldn't be lazyloaded to comply with Google PageSpeed recommendation.
  • Hidden images that the visitor does not immediately consume, and therefore, should be lazyloaded for better performance. 
The following helper plugin makes it possible to exclude the first images from lazyloading.
The only requirement is that the images have a unique attribute (a class, for example) inside the <img> tag. 

<ul>
	<li><a href="#"><img src="//wp-content/uploads/img-1" class="attachment-shop_catalog size-shop_catalog wp-post-image" alt=""></a></li>
	<li><a href="#"><img src="//wp-content/uploads/img-1" class="attachment-shop_catalog size-shop_catalog wp-post-image" alt=""></a></li>
	<li><a href="#"><img src="//wp-content/uploads/img-1" class="attachment-shop_catalog size-shop_catalog wp-post-image" alt=""></a></li>
</ul>

In this example, the <img> has a unique attribute class="attachment-shop_catalog size-shop_catalog wp-post-image" that we can use to target these images.

You can use the helper plugin as follows to target the right images to exclude:

  1. Download the helper plugin zip file, then un-zip it.
  2. Open the PHP file in a text editor.
  3. Change line 20 to target a specific image attribute.
    $pattern = 'class="attachment-shop_catalog';
  4. Make sure you keep the class=" part.
  5. Change the number in line 23 to specify the number of images containing the pattern you want to exclude.
    $count = 3;
  6. Re-zip the folder.
  7. Install the helper plugin on your site - go to Plugins → Add New → Upload plugin and select the zip file.
  8. Activate the plugin.
  9. Clear WP Rocket's cache.

📥   Download (.zip):  WP Rocket | Exclude X First Images by Attribute
Developers: You can find the code for this plugin on GitHub.

Did this answer your question? Thanks for the feedback There was a problem submitting your feedback. Please try again later.