1.1.1 • Published 3 years ago
lazyload-srcset v1.1.1
LazyLoad srcset
Lazyload images with a srcset for better performance. Also creates background-image on parent element if browser doesn't support object-fit.
Installation
Using NPM:
npm install lazyload-srcset --save
Using Yarn:
yarn add lazyload-srcset
How to use
Make sure the image elements on the page have a data-srcset instead of a srcset attribute. Set the src to a low resolution image.
<img src="lowres.jpg" data-srcset="lowRes.jpg 400w, medRes.jpg 800w, highRes.jpg 1600w" sizes="100vw" alt="Example">
Import the library in and run on init. You can pass the parent element of images to lazyload as a parameter. Defaults to body.
import lazyLoadSrcSet from 'lazyload-srcset';
const init = () => {
const scope = document.getElementById('container');
lazyLoadSrcSet(scope);
};
window.addEventListener('load', init, false);
If the parent of the image has data-bg
as attribute and the browser doesn't support object-fit
, the parent element will get the image as background-image
with background-size: cover
.
Dynamic content
If your content is dynamic (for example when using React), you can give a second parameter so that the srcset is set on the onload
event of the img.
lazyLoadSrcSet(scope, true);