Author: | ApoorvSaxena |
---|---|
Views Total: | 2,713 views |
Official Page: | Go to website |
Last Update: | September 6, 2020 |
License: | MIT |
Preview:

Description:
Lozad is a small (569 bytes minified & gzipped), highly performant JavaScript library used to lazy load Html elements (e.g. images, iframes, backgrounds, etc.) using Intersection Observer Web API.
Installation:
# Yarn $ yarn add lozad # NPM $ npm install lozad --save # Bower $ bower install lozad
How to use it:
Include the minified version of the Lozad.js on the html page.
<script src="lozad.min.js"></script>
Or include the JavaScript file from CDN:
<script src="//cdn.jsdelivr.net/npm/lozad"></script>
Initialize the Lozad and we’re ready to go.
const observer = lozad(); observer.observe();
Lazy load an image.
<img class="lozad" data-src="image.jpg" />
Lazy load responsive images.
<img class="lozad" data-src="image.jpg" data-srcset="image.jpg 960w, image-2x.jpg 2048w" />
Lazy load background image(s).
<div class="lozad" data-background-image="bg.jpg"> </div> <!-- multiple bg images --> <div class="lozad" data-background-image="bg1.jpg, bg2.jpg, bg3.jpg"> </div> <!-- responsive bg images --> <div class="lozad" data-background-image-set="url('bg.jpg') 1x, url('[email protected]') 2x"> </div>
Lazy load iframe elements.
<iframe data-src="iframe.html" class="lozad"></iframe>
The library also supports the picture tag.
<picture class="lozad" data-iesrc="1.jpg" data-alt=""> <source srcset="1.jpg" media="(min-width: 1280px)"> <source srcset="2" media="(min-width: 980px)"> <source srcset="3" media="(min-width: 320px)"> </picture>
Use the library to apply an active class to the element when it is scrolled into view.
<div data-toggle-class="active" class="lozad"> Any content here </div>
Override the default selector. Default: ‘lazad’.
const observer = lozad(el);
More configuration options.
const observer = lozad(el,{ // CSS Margin rootMargin: '10px 0px', // ratio of image convergence threshold: 0.1 });
Customize the load function.
const observer = lozad(el,{ load: function(el) { console.log('loading element'); // e.g. el.src = el.getAttribute('data-src'); } });
Changelog:
09/06/2020
- v1.16.0: Picture tag can now handle an inside img tag if it exists
05/23/2020
- v1.15.0: update
10/19/2019
- v1.14.0: update
10/18/2019
- v1.12.0: update
09/30/2019
- v1.11.0: update
06/06/2019
- v1.10.0: update
02/10/2019
- v1.9.0: Html5 video element lazyloading
11/09/2018
- Improve compatibility of data-srcset with older browsers
10/10/2018
- Expose IntersectionObserver object
09/19/2018
- Fixed load() is not triggered sometimes
v1.6.0 (09/16/2018)
- FIX: throwing an error during SSR
- Added Intersection observer options root
v1.5.0 (07/17/2018)
- alt attribute on lazy-loaded <picture> tags
- Support toggling class