Pure JavaScript Library For Lazy Loading Images & Videos – lazyload.js

Category: Javascript , Loading , Recommended | April 2, 2024
Author:verlok
Views Total:267 views
Official Page:Go to website
Last Update:April 2, 2024
License:MIT

Preview:

Pure JavaScript Library For Lazy Loading Images & Videos – lazyload.js

Description:

lazyload.js is a stand-alone JavaScript library for lazy loading images, videos, and iframes without any dependencies.

It supports the srcset attribute and with and takes the best advantage from the progressive JPEG image format. Retina (HiDPI) HiDPI screens are supported as well.

It also supports the native lazy loading feature introduced by Google.

Basic Usage:

Load the lazyload.js JavaScript library at the end of your document.

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

Insert your images into the document using data-original attribute instead 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 also supports 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 images:

<a
  href="#"
  class="lazy"
  data-bg-multi="url('1.jpg')"
  data-bg-multi-hidpi="url('full.jpg')"
></a>
// OR
<div class="lazy" 
     data-bg-set="url('[email protected]') 1x, url('[email protected]') 2x">
     ...
</div>
// OR
<div class="lazy" 
     data-bg-set="
       url('[email protected]') 1x, url('[email protected]') 2x | 
       url('[email protected]') 1x, url('[email protected]') 2x
     ">
     ...
</div>

And iframes.

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

And objects.

<object type="image/svg+xml" class="lazy" data-src="1.svg" title="Title"></object>
<object type="application/pdf" class="lazy" data-src="1.pdf" title="Title"></object>

Initialize the lazy load functionality on your images with one JS call.

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

Available options 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,
// restore original attributes on error.
restore_on_error: false,

Callback functions.

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 methods 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();
// reset all
LazyLoad.restoreAll();
// static method
LazyLoad.load(element, settings);

Get the number of images that are currently downloading from the network.

instance.loadingCount

Get the number of images to be downloaded.

instance.toLoadCount

Changelog:

v19.1.1 (04/02/2024)

  • Update

v19.0 (03/28/2024)

  • Update

v18.0 (03/28/2024)

  • Dropped support for Internet Explorer 11
  • Modernized code
  • Smaller file

v17.9 (03/20/2024)

  • Allowing to pass empty string (“”) as value for class options (class_loading, class_applied, class_loaded, class_error, class_entered, class_exited) so that no DOM mutation will happen if not necessary. This is a potential performance improvement.

v17.8.3 (07/22/2022)

  • Bugfix

v17.8.2 (05/26/2022)

  • Fixed a bug which occurred if the network connection went off and on again after a LazyLoad instance was destroyed

v17.8.1 (04/25/2022)

  • Updated Typescript typings

v17.8 (04/25/2022)

  • Added the ability to lazyload background images with CSS image-set() via data-bg-set.

v17.7 (04/10/2022)

  • Added the new option restore_on_error to restore original attributes on error.

v17.6 (02/20/2022)

  • Added ability to lazily load the <object> tag. Useful to lazily load animated SVGs.

v17.5 (09/23/2021)

  • Added the ability to restore DOM to its original state through the restoreAll() method.

v17.4 (06/07/2021)

  • Adding native lazy loading for videos

v17.3 (11/24/2020)

  • Added class_entered and class_exited options to apply a class when an element entered and/or exited the viewport

v17.2 (11/24/2020)

  • Rolling back the “data attribute cleanup” feature that was released on 16.1.0 and was causing issues when more than one instance of LazyLoad were working on the same elements of the page – the script is also 500 bytes lighter now

v17.2 (08/22/2020)

  • Fixed TypeScript typings

v17.1 (07/02/2020)

  • Unobserve all elements on loadAll() call. It’s better for performance
  • Bug fix: callback_exit() was not being called on non-image elements

v17.0 (06/25/2020)

  • The elements_selector option now defaults to .lazy
  • The cancel_on_exit option now defaults to true

v16.1 (05/21/2020)

  • Improved speed, cleaning DOM, better working destroy, and also fixed 2 bugs.

v16.0 (05/14/2020)

  • Removed call to deprecated callback_reveal
  • Removed deprecated instance load() method in favor of the static LazyLoad.load() method
  • Replaced auto_unobserve with unobserve_completed, still defaulting to true
  • Introduced a new unobserve_entered option (useful to execute lazy functions once)
  • Renamed instance method resetElementStatus() to the static LazyLoad.resetStatus()
  • Removed the load_delay option since there’s no more use for it
  • Removed the load_delay related demos
  • implified management of the cancel_on_exit with less increase/decrease of the toLoadCount property
  • Refactored counters functions in a new lazyload.counters file

v15.2 (05/07/2020)

  • New options & methods
  • Bugs fixed.
  • Improved script performance by reducing the number of event listeners used for loading elements.

v15.1 (04/01/2020)

  • Lazy background images just gained support for hiDPI (“retina”) screens. Place your standard resolution images in the data-bg attribute and your hiDPI images in data-bg-hidpi.
    Same for data-bg-multi and data-bg-multi-hidpi.

v15.0.0 (03/31/2020)

  • Lazy loading of one background image using the data-bg attribute, now manages the load and error events, so they are applied the classes defined in the class_loading/class_loaded/class_error, and the callbacks defined in callback_loading/callback_loaded/callback_error.
  • Lazy loading of multiple background images is still possible via the data-bg-multi attribute. In this case, the load and error events are not managed. The class_applied and callback_applied can be used to understand when the multiple background was applied to the element.

v14.0.0 (03/25/2020)

  • Major refactoring and performance improvement!

v14.0.0 (03/25/2020)

  • Major refactoring and performance improvement!
  • callback_loading is called when an element started loading
  • callback_reveal is now DEPRECATED, use callback_loading instead
  • update() method now also unobserves deleted elements, instead of just looking for and observing new elements
  • destroy() destroys better than it did before, delete-ing properties instead of setting their values to null
  • load() method (as an instance method) is now DEPRECATED, use the static method instead. If you were using aLazyLoadInstance.load(element) you should change it to LazyLoad.load(element, settings).
  • load() was added as a static method. Note that if you need to use custom settings, you need to pass them in the settings parameter.
  • Added toLoadCount. It’s the counter of the elements that haven’t been lazyloaded yet.
  • Removed the data-was-processed attribute, that was added to mark lazy DOM elements as “already managed”. If you were manually handling that attribute to obtain some goal, this is a potentially breaking change. You should now refer to the data-ll-status instead.
  • Added the data-ll-status attribute, which is now used to mark the status of a lazy DOM element. The values it can take are: observing (not loaded yet), loading (loading started), loaded (load completed), error (an error has occured), native (similar to observing, but managed by native lazy loading).

v13.0.1 (03/07/2020)

  • Fixed a JS error that could happen to IE11 users after going offline and back online
  • Minor refactoring for better readibility and lighter code (and files)!

v13.0 (03/01/2020)

  • Added the minified version of dist/lazyload.esm.js as dist/lazyload.esm.min.js, so now you can effortlessly use it with an ES module import statement when using type=”module”
  • Reduced files weight even more! dist/lazyload.iife.min.js now weights only 2.03 KB GZipped
  • Removed the callback_set callback that was deprecated since version 11 in favour of callback_reveal
  • Removed sourcemaps (they were probably used only by the authors, but if anyone was actually needing them, we can bring them back)
  • Hidden the _extends function inside LazyLoad’s scope (it was global before)
  • Updated build tooling: removed Gulp, now using Rollup & Babel only

v12.5.1 (02/29/2020)

  • Restored IE11 compatibility.

v12.5.0 (02/25/2020)

  • The once-private _loadingCount property is now public and renamed to loadingCount. This property contains the number of images that are currently downloading from the network, limitedly to the ones managed by an instance of LazyLoad. This is particularly useful to understand whether or not is safe to destroy an instance of LazyLoad.

v12.4.0 (11/21/2019)

  • Video posters can now be loaded lazily via data-poster attribute.

v12.3.0 (10/31/2019)

  • Callbacks now pass more arguments!

v12.2.0 (10/22/2019)

  • Released new feature “retry when back online”. Now if your users lose the internet connection causing errors on images loading, this script tries and loads those images again when the connection is restored.

v12.1.0 (10/07/2019)

  • Updated
  • Added more demos in the zip

v12.0.0 (04/27/2019)

  • Reorganized code
  • Improved native lazy loading demos
  • Aligned console messages throughout all demos.

v12.0.0beta (03/23/2019)

  • Added the use_native option which enables native lazy loading (where supported) with the loading=”lazy” attribute.
  • Refactored the constructor and the update method

v11.0.6 (03/23/2019)

  • Restored the callback_set callback as deprecated, in order to make the upgrade from v.10 easier.

v11.0.5 (03/15/2019)

  • Fixed the module property of this package.json, which was pointing to a non-existing dist file.
  • Fixed the main property of this package.json, which was pointing to a non-existing dist file.
  • Rollback of the patch applied in 11.0.2 since it gave strange results in some cases.

v11.0.2 (03/02/2019)

  • Squashed a nasty bug that occurred on IE 11 and Safari when the IntersectionObserver polyfill wasn’t loaded before LazyLoad.
  • Fixed a Chromium bug.

v11.0.0 (02/24/2019)

  • Changed bundle file name of ES Module from lazyload.es2015.js to lazyload.esm.js
  • Removed the to_webp option
  • Callback callback_enter has changed its meaning! It is now called whenever an element enters the viewport, even if load_delay is set
  • Callback callback_exit (new) is called whenever an element exits the viewport, even if load_delay is set
  • Callback callback_reveal (new) is called when an element is about to be revealed, and its attribute values were copied from the data- attributes to the actual ones.
  • Callback callback_set was removed. You can use callback_reveal instead.
  • Private methods like _setObserver, _onIntersection etc. are now hidden and protected.
  • Added the auto_unobserve boolean option.
  • Bugfix: loadAll() didn’t unobserve elements.

v10.20.0 (02/09/2019)

  • Improved WebP detection to work correctly on Firefox too
  • Added the ability to know when all images have been downloaded through the callback_finish callback
  • Added the file demos/print.html to demo how to print lazy images

09/29/2018

  • v10.18: Added the ability to have multiple background images, through a new data_bg option.-in-javascript

09/13/2018

  • v10.17: Added a new thresholds option that you can use when you need to have different thresholds for the scrolling area, so a single threshold option is not enough for your needs.

08/18/2018

  • v10.16: Added new option load_delay to skip loading when fast scrolling occurs. Pass in a number of milliseconds, and each image will be loaded after it stayed inside that viewport for that time.

08/04/2018

  • v10.13: Shortened the RegEx for crawlers detection

07/21/2018

  • v10.10: Added a public load method to force loading any element.

07/14/2018

  • v10.9: Added the ability to lazily set the sizes attribute via a data-sizes attribute.

06/24/2018

  • v10.8: Added a public loadAll method to force loading all the images

05/31/2018

  • v10.5.2: Added a security check on lazy elements’ parents.

You Might Be Interested In:


Leave a Reply