Press "Enter" to skip to content

Lazy Loading Images, Backgrounds, Videos & Iframes | lazyload.js

LazyLoad is a lightweight (2.4KB) and flexible script that speeds up your web application by delaying the loading of images, videos, and iframes at the bottom of the page until the time they enter the viewport. It’s written in “vanilla” JavaScript, takes advantage of the IntersectionObserver API, supports responsive images, optimizes your website for slower connections, and can enable native lazy loading.

To a polyfill or not to a polyfill IntersectionObserver?

In a browser that does not support IntersectionObserver such as Internet Explorer and earlier versions of Safari, you can choose whether or not to add a javascript polyfill for it.

lazy loading images, lazy loading images jquery, benefits of lazy loading images, loadinglazy, lazy load, lazy loading javascript, loadinglazy html

How to make use of it:

Load the lazyload.js JavaScript library on the finish of your doc.

<script src="path/to/lazyload.js"></script>

Insert your photos into the doc utilizing data-original attribute as an alternative of src.

// single image
<img data-src="1.jpg" alt="Alt 1" /> 
// with low-quality placeholder
<img src="thumb-1.jpg"
     data-src="1.jpg"
     alt="Alt 1"
/>

// responsive image
<img class="lazy"
     data-src="1.jpg"
     data-srcset="1_400.jpg 400w, 1_800.jpg 800w"
     data-sizes="100w"
     alt="Alt 1"
/>

// with Picture element
<picture>
  <source media="(min-width: 1200px)"
          data-srcset="1_1200.jpg 1x, 1_2400.jpg 2x"
  />
  <source media="(min-width: 800px)"
          data-srcset="1_800.jpg 1x, 1_1600.jpg 2x"
  />
  <img class="lazy"
       data-src="1.jpg"
       alt="Alt 1"
  />
</picture>

// Works with webp format
<picture>
  <source type="image/webp"
         data-srcset="1.webp 400w, 1.webp 800w"
         data-sizes="100w"
  />
  <img class="lazy"
       data-src="1.jpg"
       data-srcset="1_400.jpg 400w, 1_800.jpg 800w"
       data-sizes="100w"
  />
</picture>

It additionally helps HTML5 videos.

<video class="lazy" controls width="620"
  data-src="lazy.mp4" data-poster="lazy.jpg">
  <source type="video/mp4" data-src="lazy.mp4">
  <source type="video/ogg" data-src="lazy.ogg">
  <source type="video/avi" data-src="lazy.avi">
</video>

And background photos:

<a
  href="#"
  class="lazy"
  data-bg-multi="url('1.jpg')"
  data-bg-multi-hidpi="url('full.jpg')"
></a>

And iframes.

<iframe class="lazy" data-src="lazyFrame.html"> </iframe>

Initialize the lazy load functionality in your photos with one JS name.

new LazyLoad({/*options*/});

Available choices with default values.

// image selector
elements_selector: ".lazy",

// parent container
container: window,

// the distance out of the viewport
threshold: 300,

// different thresholds
thresholds: null,

// data-src
data_src: "src",

// data-srcset
data_srcset: "srcset",

// date-sizes
data_sizes: "sizes",

// for background images
data_bg: "bg",

// for hidpi images
data_bg_hidpi: "bg-hidpi",

// for multiple bg images
data_bg_multi: "bg-multi",
data_bg_multi_hidpi: "bg-multi-hidpi",

// for poster image
data_poster: "poster",

// default classes
class_applied: "applied",
class_loading: "loading",
class_loaded: "loaded",
class_error: "error",
class_entered: "entered",
class_exited: "exited",

// whether or not to automatically unobserve elements that was already revealed
unobserve_completed: true,

// execute lazy functions once
unobserve_entered: true,

// true = cancel the download of images exiting the viewport while still loading, eventually restoring the original attributes
cancel_on_exit: true,

// use native loading attribute
use_native: false

Callback features.

new LazyLoad({
    callback_enter: function(DOM, IntersectionObserverEntry, instance){
      // do something
    },
    callback_exit: function(DOM, IntersectionObserverEntry, instance){
      // do something
    },
    callback_applied: function(DOM, instance){
      // do something
    },
    callback_loading: function(DOM, instance){
      // do something
    },
    callback_loaded: function(DOM, instance){
      // do something
    },
    callback_error: function(DOM, instance){
      // do something
    },
    callback_finish: function(instance){
      // do something
    },
    callback_cancel: function(instance){
      // do something
    }
});

API strategies and properties.

// the number of elements that are currently downloading from the network (limitedly to the ones managed by the instance of LazyLoad). 
instance.loadingCount

// the number of elements that haven't been lazyloaded yet (limitedly to the ones managed by the instance of LazyLoad)
instance.toLoadCount

// update the LazyLoad
instance.update();

// force loading any element
instance.load(element, force);

// load all images
instance.loadAll();

// destroy the LazyLoad
instance.destroy();

// reset the internal status of the given element.
LazyLoad.resetStatus();

// static method
LazyLoad.load(element, settings);

Get the variety of photos that are presently downloading from the community.

instance.loadingCount

Get a variety of photos to be downloaded.

instance.toLoadCount

Options

For every instance of LazyLoad you can pass in some options, to alter its default behaviour. Here’s the list of the options.

NameMeaningDefault valueExample value
containerThe scrolling container of the elements in the elements_selector option.documentdocument.querySelector('.scrollPanel')
elements_selectorThe CSS selector of the elements to load lazily, which will be selected as descendants of the container object.".lazy"".lazyload"
thresholdA number of pixels representing the outer distance off the scrolling area from which to start loading the elements.3000
thresholdsSimilar to threshold, but accepting multiple values and both px and % units. It maps directly to the rootMargin property of IntersectionObserver (read more), so it must be a string with a syntax similar to the CSS margin property. You can use it when you need to have different thresholds for the scrolling area. It overrides threshold when passed.null"500px 10%"
data_srcThe name of the data attribute containing the element URL to load, excluding the "data-" part. E.g. if your data attribute is named "data-src", just pass "src""src""lazy-src"
data_srcsetThe name of the data attribute containing the image URL set to load, in either img and source tags, excluding the "data-" part. E.g. if your data attribute is named "data-srcset", just pass "srcset""srcset""lazy-srcset"
data_sizesThe name of the data attribute containing the sizes attribute to use, excluding the "data-" part. E.g. if your data attribute is named "data-sizes", just pass "sizes""sizes""lazy-sizes"
data_bgThe name of the data attribute containing the URL of background-image to load lazily, excluding the "data-" part. E.g. if your data attribute is named "data-bg", just pass "bg". The attribute value must be a valid value for background-image, including the url() part of the CSS instruction."bg""lazy-bg"
data_bg_hidpiThe name of the data attribute containing the URL of background-image to load lazily on HiDPI screens, excluding the "data-" part. E.g. if your data attribute is named "data-bg-hidpi", just pass "bg-hidpi". The attribute value must be a valid value for background-image, including the url() part of the CSS instruction."bg-hidpi""lazy-bg-hidpi"
data_bg_multiThe name of the data attribute containing the value of multiple background-image to load lazily, excluding the "data-" part. E.g. if your data attribute is named "data-bg-multi", just pass "bg-multi". The attribute value must be a valid value for background-image, including the url() part of the CSS instruction."bg-multi""lazy-bg-multi"
data_bg_multi_hidpiThe name of the data attribute containing the value of multiple background-image to load lazily on HiDPI screens, excluding the "data-" part. E.g. if your data attribute is named "data-bg-multi-hidpi", just pass "bg-multi-hidpi". The attribute value must be a valid value for background-image, including the url() part of the CSS instruction."bg-multi-hidpi""lazy-bg-multi-hidpi"
data_posterThe name of the data attribute containing the value of poster to load lazily, excluding the "data-" part. E.g. if your data attribute is named "data-poster", just pass "poster"."poster""lazy-poster"
class_appliedThe class applied to the multiple background elements after the multiple background was applied"applied""lazy-applied"
class_loadingThe class applied to the elements while the loading is in progress."loading""lazy-loading"
class_loadedThe class applied to the elements when the loading is complete."loaded""lazy-loaded"
class_errorThe class applied to the elements when the element causes an error."error""lazy-error"
class_enteredThe class applied to the elements after they entered the viewport."entered""lazy-entered"
class_exitedThe class applied to the elements after they exited the viewport. This class is removed if an element enters the viewport again. The unobserve_entered option can affect the appliance of this class, e.g. when loading images that complete loading before exiting."exited""lazy-exited"
cancel_on_exitA boolean that defines whether or not to cancel the download of the images that exit the viewport while they are still loading, eventually restoring the original attributes. It applies only to images so to the img (and picture) tags, so it doesn’t apply to background images, iframes nor videos.truefalse
unobserve_enteredA boolean that defines whether or not to automatically unobserve elements once they entered the viewportfalsetrue
unobserve_completedA boolean that defines whether or not to automatically unobserve elements once they’ve loaded or throwed an errortruefalse
callback_enterA callback function which is called whenever an element enters the viewport. Arguments: DOM element, intersection observer entry, lazyload instance.null(el)=>{console.log("Entered", el)}
callback_exitA callback function which is called whenever an element exits the viewport. Arguments: DOM element, intersection observer entry, lazyload instance.null(el)=>{console.log("Exited", el)}
callback_loadingA callback function which is called whenever an element starts loading. Arguments: DOM element, lazyload instance.null(el)=>{console.log("Loading", el)}
callback_cancelA callback function which is called whenever an element loading is canceled while loading, as for cancel_on_exit: true.null(el)=>{console.log("Cancelled", el)}
callback_loadedA callback function which is called whenever an element finishes loading. Note that, in version older than 11.0.0, this option went under the name callback_load. Arguments: DOM element, lazyload instance.null(el)=>{console.log("Loaded", el)}
callback_errorA callback function which is called whenever an element triggers an error. Arguments: DOM element, lazyload instance.null(el)=>{console.log("Error", el)}
callback_appliedA callback function which is called whenever a multiple background element starts loading. Arguments: DOM element, lazyload instance.null(el)=>{console.log("Applied", el)}
callback_finishA callback function which is called when there are no more elements to load and all elements have been downloaded. Arguments: lazyload instance.null()=>{console.log("Finish")}
use_nativeThis boolean sets whether or not to use native lazy loading to do hybrid lazy loading. On browsers that support it, LazyLoad will set the loading="lazy" attribute on images, iframes and videos, and delegate their loading to the browser.falsetrue

Methods

Instance methods

You can call the following methods on any instance of LazyLoad.

Method nameEffectUse case
update()Make LazyLoad to re-check the DOM for elements_selector elements inside its container.Update LazyLoad after you added or removed DOM elements to the page.
loadAll()Loads all the lazy elements right away and stop observing them, no matter if they are inside or outside the viewport, no matter if they are hidden or visible.To load all the remaining elements in advance
destroy()Destroys the instance, unsetting instance variables and removing listeners.Free up some memory. Especially useful for Single Page Applications.

Properties

You can use the following properties on any instance of LazyLoad.

Property nameValue
loadingCountThe number of elements that are currently downloading from the network (limitedly to the ones managed by the instance of LazyLoad). This is particularly useful to understand whether or not is safe to destroy this instance of LazyLoad.
toLoadCountThe number of elements that haven’t been lazyloaded yet (limitedly to the ones managed by the instance of LazyLoad)

Lazy Loading Images & Videos, LazyLoad Plugin/Github


See Demo And Download

Official Website(verlok): Click Here

This superior jQuery/javascript plugin is developed by verlok. For extra advanced usage, please go to the official website.

Be First to Comment

    Leave a Reply

    Your email address will not be published.