Help me understand why product images are missing the HTML ‘loading’ attribute
-
I don’t understand why images in certain Woocommerce product loops aren’t making use of native browser lazy loading.
As I understand it, by default, WordPress will add a
loading="lazy"
attribute to images. However if you checkout the Storefront theme demo for example all images on the homepage e.g ‘Product Categories’, ‘Recent Products’, ‘Top rated Products’ etc. are missing the loading attribute. Why is this? The images in the product loop on the ‘Shop‘ page do correctly have aloading="lazy"
attribute.I feel these all should be taking advantage of lazy loading by default for performance reasons.
As an aside what is the best filter to use to add the attribute and enable lazy loading? I’ve come up with the below using wp_get_attachment_image_attributes:
function shano_enable_lazy_loading($attr, $attachment, $size){
// Check if image has .attachment-woocommerce_thumbnail class
if ( str_contains($attr['class'], 'attachment-woocommerce_thumbnail') ) {
$attr['loading'] = 'lazy';
}
return $attr;
}
add_filter('wp_get_attachment_image_attributes', 'shano_enable_lazy_loading', 10, 3);
- You must be logged in to reply to this topic.