lozad.js
🔥 Highly performant, light ~1kb and configurable lazy loader in pure JS with no dependencies for responsive images, iframes and more
Top Related Projects
Vanilla JavaScript plugin for lazyloading images
High performance and SEO friendly lazy loader for images (responsive and normal), iframes and more, that detects any visibility changes triggered through user interaction, CSS or JavaScript without configuration.
A fast, flexible, and small SEO-friendly lazy loader.
Hey, be lazy! bLazy.JS is a lightweight pure JavaScript script for lazy loading and multi-serving images. It's working in all modern browsers including IE7+.
Quick Overview
Lozad.js is a lightweight, high-performance JavaScript library for lazy loading images and other DOM elements. It uses the Intersection Observer API to efficiently detect when elements enter the viewport, making it an excellent choice for optimizing web page performance by deferring the loading of off-screen content.
Pros
- Extremely lightweight (less than 1KB gzipped)
- Uses Intersection Observer API for better performance
- No dependencies required
- Supports various content types (images, iframes, videos, etc.)
Cons
- Requires polyfill for older browsers that don't support Intersection Observer API
- Limited built-in customization options
- May not be suitable for complex lazy loading scenarios without additional configuration
Code Examples
- Basic usage for lazy loading images:
const observer = lozad();
observer.observe();
- Lazy loading with custom options:
const observer = lozad('.lozad', {
rootMargin: '10px 0px',
threshold: 0.1,
loaded: function(el) {
el.classList.add('loaded');
}
});
observer.observe();
- Manually triggering load for specific elements:
const element = document.querySelector('.lozad');
const observer = lozad(element);
observer.observe();
// Trigger loading of a specific element
observer.triggerLoad(element);
Getting Started
- Include the Lozad.js library in your HTML:
<script src="https://cdn.jsdelivr.net/npm/lozad@1.16.0/dist/lozad.min.js"></script>
- Add the
lozad
class to elements you want to lazy load:
<img class="lozad" data-src="image.jpg" alt="My image">
- Initialize Lozad in your JavaScript:
document.addEventListener('DOMContentLoaded', function() {
const observer = lozad();
observer.observe();
});
This setup will lazy load all elements with the lozad
class. For images, use data-src
instead of src
to specify the image source.
Competitor Comparisons
Vanilla JavaScript plugin for lazyloading images
Pros of lazyload
- More feature-rich, supporting various loading techniques (e.g., LQIP, SQIP)
- Better browser compatibility, including older versions
- More customizable with a wider range of options
Cons of lazyload
- Larger file size, potentially impacting page load times
- More complex setup and configuration
- Less frequently updated compared to lozad.js
Code Comparison
lozad.js:
const observer = lozad();
observer.observe();
lazyload:
const lazyLoadInstance = new LazyLoad({
elements_selector: ".lazy",
load_delay: 300
});
Both libraries aim to provide lazy loading functionality, but lozad.js focuses on simplicity and performance, while lazyload offers more features and customization options. lozad.js uses the Intersection Observer API, making it more modern but potentially less compatible with older browsers. lazyload, on the other hand, provides fallbacks for broader browser support.
The code comparison shows that lozad.js has a simpler setup process, requiring just two lines of code to initialize and observe elements. lazyload requires more configuration but allows for greater customization of lazy loading behavior.
Ultimately, the choice between these libraries depends on project requirements, target browser support, and desired level of customization.
High performance and SEO friendly lazy loader for images (responsive and normal), iframes and more, that detects any visibility changes triggered through user interaction, CSS or JavaScript without configuration.
Pros of lazysizes
- More feature-rich, offering advanced functionality like automatic size calculation and LQIP (Low-Quality Image Placeholder) support
- Wider browser compatibility, including older versions of Internet Explorer
- Extensive plugin ecosystem for additional features and customization
Cons of lazysizes
- Larger file size (around 10KB minified and gzipped) compared to lozad.js
- More complex setup and configuration, which may be overkill for simpler projects
- Higher CPU usage due to more extensive features and calculations
Code Comparison
lazysizes:
<img data-src="image.jpg" class="lazyload" />
<script src="lazysizes.min.js"></script>
lozad.js:
<img data-src="image.jpg" class="lozad" />
<script src="lozad.min.js"></script>
<script>
const observer = lozad();
observer.observe();
</script>
Both libraries use similar markup for lazy loading images, but lozad.js requires explicit initialization of the observer. lazysizes automatically starts working once the script is loaded, making it slightly easier to implement for basic use cases. However, lozad.js offers more control over when and how the lazy loading is initiated.
A fast, flexible, and small SEO-friendly lazy loader.
Pros of yall.js
- Supports more types of media (images, videos, iframes) out of the box
- Offers more customization options for loading behavior
- Includes built-in support for WebP format detection
Cons of yall.js
- Slightly larger file size compared to lozad.js
- May have a steeper learning curve due to more configuration options
- Less frequent updates and maintenance
Code Comparison
lozad.js:
const observer = lozad();
observer.observe();
yall.js:
document.addEventListener("DOMContentLoaded", yall);
Both libraries offer simple initialization, but yall.js can be more concise in basic usage scenarios.
Summary
yall.js provides more comprehensive lazy loading capabilities and customization options, making it suitable for complex projects with diverse media types. However, lozad.js offers a lighter-weight solution with a simpler API, which may be preferable for projects with basic lazy loading needs. The choice between the two depends on the specific requirements of your project and the level of control you need over lazy loading behavior.
Hey, be lazy! bLazy.JS is a lightweight pure JavaScript script for lazy loading and multi-serving images. It's working in all modern browsers including IE7+.
Pros of bLazy
- Smaller file size (2KB minified and gzipped) compared to Lozad.js (1.9KB gzipped)
- Supports more legacy browsers, including IE7+
- Offers more customization options out of the box
Cons of bLazy
- Less actively maintained (last update in 2018)
- Slightly more complex API and setup process
- Lacks some modern features like native lazy loading support
Code Comparison
bLazy initialization:
var bLazy = new Blazy({
selector: 'img',
offset: 100,
success: function(element){
console.log("Element loaded");
}
});
Lozad.js initialization:
const observer = lozad('.lozad', {
rootMargin: '10px 0px',
threshold: 0.1,
loaded: function(el) {
console.log("Element loaded");
}
});
observer.observe();
Both libraries aim to provide lazy loading functionality for images and other elements, but they differ in their approach and feature set. bLazy offers more legacy browser support and customization options, while Lozad.js focuses on modern browsers and leverages the Intersection Observer API for better performance. The choice between the two depends on specific project requirements and target browser support.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
Lozad.js
Highly performant, light and configurable lazy loader in pure JS with no dependencies for images, iframes and more, using IntersectionObserver API
Lozad.js:
- lazy loads elements performantly using pure JavaScript,
- is a light-weight library, just minified & gzipped,
- has NO DEPENDENCIES :)
- allows lazy loading of dynamically added elements as well,
- supports <img>, <picture>, iframes, videos, audios, responsive images, background images and multiple background images etc.
- even supports LQIP (Low Quality Image Placeholder)
- is completely free and open source.
- it will reload when the valid attributes change.
It is written with an aim to lazy load images, iframes, ads, videos or any other element using the recently added Intersection Observer API and MutationObserver with tremendous performance benefits.
Featured in:
Brands using Lozad.js:
and many more...
Table of Contents
- Demo
- Background
- Install
- Usage
- Example with picture tag
- Browser Support
- FAQs
- Contribute
- Changelog
- License
Yet another Lazy Loading JavaScript library, why?
Existing lazy loading libraries hook up to the scroll event or use a periodic timer and call getBoundingClientRect()
on elements that need to be lazy loaded. This approach, however, is painfully slow as each call to getBoundingClientRect()
forces the browser to re-layout the entire page and will introduce considerable jank to your website.
Making this more efficient and performant is what IntersectionObserver is designed for, and itâs landed in Chrome 51. IntersectionObservers let you know when an observed element enters or exits the browserâs viewport.
Install
# You can install lozad with npm
$ npm install --save lozad
# Alternatively you can use Yarn
$ yarn add lozad
# Another option is to use Bower
$ bower install lozad
Then with a module bundler like rollup or webpack, use as you would anything else:
// using ES6 modules
import lozad from 'lozad'
// using CommonJS modules
var lozad = require('lozad')
Or load via CDN and include in the head
tag of your page.
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/lozad/dist/lozad.min.js"></script>
When loading from CDN, you can find the library on window.lozad
.
Usage
In HTML, add an identifier to the element (default selector identified is lozad
class):
<img class="lozad" data-src="image.png">
All you need to do now is just instantiate Lozad as follows:
const observer = lozad(); // lazy loads elements with default selector as '.lozad'
observer.observe();
or with a DOM Element
reference:
const el = document.querySelector('img');
const observer = lozad(el); // passing a `NodeList` (e.g. `document.querySelectorAll()`) is also valid
observer.observe();
or with custom options:
const observer = lozad('.lozad', {
rootMargin: '10px 0px', // syntax similar to that of CSS Margin
threshold: 0.1, // ratio of element convergence
enableAutoReload: true // it will reload the new image when validating attributes changes
});
observer.observe();
Reference:
or if you want to give custom function definition to load element:
lozad('.lozad', {
load: function(el) {
console.log('loading element');
// Custom implementation to load an element
// e.g. el.src = el.getAttribute('data-src');
}
});
If you would like to extend the loaded
state of elements, you can add the loaded option:
Note: The
"data-loaded"="true"
attribute is used by lozad to determine if an element has been previously loaded.
lozad('.lozad', {
loaded: function(el) {
// Custom implementation on a loaded element
el.classList.add('loaded');
}
});
If you want to lazy load dynamically added elements:
const observer = lozad();
observer.observe();
// ... code to dynamically add elements
observer.observe(); // observes newly added elements as well
for use with responsive images
<!-- responsive image example -->
<img class="lozad" data-src="image.png" data-srcset="image.png 1000w, image-2x.png 2000w">
for use with background images
<!-- background image example -->
<div class="lozad" data-background-image="image.png">
</div>
for use with multiple background images
<!-- multiple background image example -->
<div class="lozad" data-background-image="path/to/first/image,path/to/second/image,path/to/third/image">
</div>
for use with responsive background images (image-set)
<!-- responsive background image-set example -->
<div class="lozad" data-background-image-set="url('photo.jpg') 1x, url('photo@2x.jpg') 2x">
</div>
To change the delimiter that splits background images:
<!-- custom delimiter for background images example -->
<div
class="lozad"
data-background-image="/first/custom,image,path/image.png-/second/custom,image,path/image.png"
data-background-delimiter="-"
>
</div>
If you want to load the images before they appear:
const observer = lozad();
observer.observe();
const coolImage = document.querySelector('.image-to-load-first');
// ... trigger the load of a image before it appears on the viewport
observer.triggerLoad(coolImage);
Large image improvment
Sometimes image loading takes a long time. For this case, you can add a placeholder background:
<img class="lozad" data-placeholder-background="red" data-src="image.png">
Lozad sets a placeholder background color of img element and users will see the fallback till the image loads.
Example with picture tag
Create a broken picture element structure.
IE browser don't support picture tag! You need to set
data-iesrc
attribute (only for your picture tags) with source for IE browser
data-alt
attribute can be added to picture tag for use inalt
attribute of lazy-loaded images
<!-- For an element to be caught, add a block type that is different from the inline and some min-height for correct caught into view -->
<picture class="lozad" style="display: block; min-height: 1rem" data-iesrc="images/thumbs/04.jpg" data-alt="">
<source srcset="images/thumbs/04.jpg" media="(min-width: 1280px)">
<source srcset="images/thumbs/05.jpg" media="(min-width: 980px)">
<source srcset="images/thumbs/06.jpg" media="(min-width: 320px)">
<!-- NO img element -->
<!-- instead of img element, there will be the last source with the minimum dimensions -->
<!-- for disabled JS you can set <noscript><img src="images/thumbs/04.jpg" alt=""></noscript> -->
</picture>
When lozad loads this picture element, it will fix it.
If you want to use image placeholder (like low quality image placeholder), you can set a temporary img
tag inside your picture
tag. It will be removed when lozad loads the picture element.
<picture class="lozad" style="display: block; min-height: 1rem" data-iesrc="images/thumbs/04.jpg" data-alt="">
<source srcset="images/thumbs/04.jpg" media="(min-width: 1280px)">
<source srcset="images/thumbs/05.jpg" media="(min-width: 980px)">
<source srcset="images/thumbs/06.jpg" media="(min-width: 320px)">
<!-- you can define a low quality image placeholder that will be removed when the picture is loaded -->
<img src="data:image/jpeg;base64,/some_lqip_in_base_64==">
</picture>
Example with video
<video class="lozad" data-poster="images/backgrounds/video-poster.jpeg">
<source data-src="video/mov_bbb.mp4" type="video/mp4">
<source data-src="video/mov_bbb.ogg" type="video/ogg">
</video>
Example with iframe
<iframe data-src="embed.html" class="lozad"></iframe>
That's all, just add the lozad
class.
Example toggling class
<div data-toggle-class="active" class="lozad">
<!-- content -->
</div>
The active
class will be toggled on the element when it enters the browserâs viewport.
Browser Support
Available in latest browsers. If browser support is not available, then make use of polyfill.
For IE11 support, please make use of these polyfills.
FAQs
Checkout the FAQ Wiki for some common gotchas to be aware of while using lozad.js
Contribute
Interested in contributing features and fixes?
Changelog
See the Changelog
License
MIT © Apoorv Saxena
Top Related Projects
Vanilla JavaScript plugin for lazyloading images
High performance and SEO friendly lazy loader for images (responsive and normal), iframes and more, that detects any visibility changes triggered through user interaction, CSS or JavaScript without configuration.
A fast, flexible, and small SEO-friendly lazy loader.
Hey, be lazy! bLazy.JS is a lightweight pure JavaScript script for lazy loading and multi-serving images. It's working in all modern browsers including IE7+.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot