The loading performance of your web shop ist crucial in terms of the page speed and conversion rate. Especially on the product archive pages a lot of images are loading. To improve this amount of requests lazy loading helps to load the items only at the moment they are entering the viewport.
The JavaScript library “Lozad.js”
Lozad.js is a popular and very flexible open source lazy loading library by Apoorv Saxena. Enqueue the following script via the functions.php of your theme.
1 2 |
wp_register_script('lozad', 'https://cdn.jsdelivr.net/npm/lozad', array(), '', false); wp_enqueue_script('lozad'); |
Via a small Script we are defining class “lozad” to be the selector for our lazy loading. Add this to the footer.php of your theme.
1 2 3 4 |
<script type="text/javascript"> const observer = lozad(); // lazy loads elements with default selector as ".lozad" observer.observe(); </script> |
Enabling lazy loading with images of woocmmerce archive
Via a hook we have to replace the standard image tag of each product item with a data-src attribute to enable lazy loading via Lozad.js. Further on the item has to have the class “lozad” as defined in our script above. Add the following code to your functions.php of your theme:
1 2 3 4 |
function woocommerce_template_loop_product_thumbnail() { $image_src = wp_get_attachment_image_src( get_post_thumbnail_id(),'thumbnail' ); echo '<img data-src="' . $image_src[0] . '" width="400" height="900" class="attachment-shop_catalog wp-post-image lozad">'; }; |
Note: The hook will replace the image tag of Woocommerce in all archive pages and for all standard shortcodes.