Lazy loading allows you to defer loading of image assets until they are needed. Typically, this is when they're about to enter the browser viewport.
This improves the initial page load times, and can be triggered through the use of a suite of data attributes:-
data-lazy-src- Replace an image's `src` attribute with this, and when the image is about to enter the viewport it will be loaded.
data-lazy-srcset- The same as the above, but with an image's
data-lazy-class- This is for images set as backgrounds through CSS. When the image enters the viewport, the value of this attribute is added as a class to the element, which should be used to add any relevant
background-imagestyles. If no value is passed to
Note: If in a browser where native lazy loading is available via
loading="lazy" attribute, use that instead for images as the module code isn't run.
Note: By accessing the
evotoolkit object in the global scope, you can refire this module on demand in case you programatically add DOM nodes after initial page load.
With lazy loaded images, it's important to supply a placeholder of the same dimensions so when the image is loaded in, the browser doesn't trigger a reflow as nothing has to be resized.
To make this process easy, a base64 transparent SVG can be added to the
src attribute. Simply change the 2 numbers in the SVGs
viewBox attribute to match the width and height values.
Here's a 400px x 350px placeholder, which has a 8:7 aspect ratio.
In Chrome developer tools, open the network tab and scroll to see the browser load in the images as required.
Scroll down and when the image is about to enter the viewport, it will be loaded in.
The next image is responsive, and requires a
srcset to function.
Finally, the last example is of a class based background image, which is added to the element and triggers a network request for the image.