Speed optimization is one of the ultimate goals of every store. That's why when trying to speed up Magento, you'll definitely come across lazy loading, one of the best ways to optimise images.
For those of you who don't know what is lazy loading, it is a loading technique that helps you to load only images available within users' viewport. This helps to improve page loading and deffer unnecessary resources.
Image lazy load configuration is not that hard but you might sometimes encounter issues with configuring the lazy load of CSS background images. And that's what we'll be working on today.
Post Contents [hide]
How Do Lazy Load Extensions Work?
Before moving any further we need to revise the basic principle used in Lazy Load extensions to learn how to apply it to the CSS background images.
By default browser loads an image added in the src attribute of the image tag during page load:
<img src="image.jpg" />
To prevent this, image lazy load is implemented. It is usually processed in two ways:
- replacing the src attribute with data-src, data-srcset, or some other attribute.
- replacing the data-src attribute with the src attribute by JS on page load or any other JS event indicating that the images should be displayed.
How to Lazy Load Background Images in Magento?
Now that we understand how lazy load works, let's try to lazy load our background images.
In case you use the Magefan Lazy Load Extension you can simply adjust the HTML and replace this line:
The extension will load the image lazy load CSS background image property.
In case you don’t have Magefan Lazy Load or don't want to change HTML, you can use CSS background property and display:none. The browser will not load images from the background CSS property if this block has display:none:
You can use this approach in the menu on mouse hover or click. So when menu items are displayed browser will also load images that are located there.
However, you should still keep in mind that lazy loading is not the only way to improve page speed. Try incorporating webp images to reduce the size of images as well.