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:
- Download the helper plugin zip file, then un-zip it.
- Open the PHP file in a text editor.
- Change line 20 to target a specific image attribute.
$pattern = 'class="attachment-shop_catalog';
Make sure you keep the
- Change the number in line 23 to specify the number of images containing the pattern you want to exclude.
$count = 3;
- Re-zip the folder.
- Install the helper plugin on your site - go to Plugins → Add New → Upload plugin and select the zip file.
- Activate the plugin.
- Clear WP Rocket's cache.
class="
part.
📥 Download (.zip): WP Rocket | Exclude X First Images by Attribute
Developers: You can find the code for this plugin on GitHub.