Responsive Lazy Loader
Responsive Lazy Loader is a lightweight script that loads your images when they enter the viewport. Not only that but it honours your responsive (srcset) images.
Installation
yarn add responsive-lazy-loader
npm install responsive-lazy-loader
Usage
Ensure your <img />
tags have a data-src
attribute with a path to your image and a default image src
. After you've initialised the script, your images will lazy load out of the box. For example:
JS:
; ;
HTML:
Once the image comes into view, it will output:
The script also takes into account srcset
and sizes
by binding them to data attributes. For example:
You can also lazyload picture tags using this ibrary. Please bear in mind that picture tag is not supported in all browsers. In order to make picture tag work you need to use a picture tag polyfill such as picturefill
Parameters
(src, srcset, sizes, callback, loadOnScroll, resizeDebounce, throttle, threshold)
parameter | description |
---|---|
src |
Type: string Default: 'data-src' The data attribute we want to use for the images src attribute.
|
srcset |
Type: string Default: 'data-srcset' The data attribute we want to use for the images srcset attribute.
|
sizes |
Type: string Default: 'data-sizes' The data attribute we want to use for the images sizes attribute.
|
callback |
Type: function Default: undefined An optional function that will be called after each image has been loaded. |
loadOnScroll |
Type: Boolean Default: true Do you want to load the images when they are in the viewport or all once? |
resizeDebounce |
Type: INT Default: 500 How long after the user stops resizing their browser window before firing the resize recalculations. |
throttle |
Type: INT Default: 250 How often the scroll event listener fires to check if the image is in view. |
threshold |
Type: INT Default: 0 How much of an offset do you want for the image to be classed as in the viewport? |
MIT