A teeny lazy loader to make your site more performant, by only loading images as they get near the viewport. 33 lines of code, 863 bytes of data (460 minified), vanilla javascript only.
- Written in Vanilla JS, no other dependencies
- Will take
data-srcattribute and load in ansrcattribute for images - If
data-srcis not on animg, lzy.js will fallback to applyingbackground-imageto element's style - Will remove the
data-srcattribute once loading is done - Can pass in an
offsetvalue which controls how far the images are from the viewport before being loaded. By default this is 200px - Uses the
intersectionObserverAPI, with a polyfill method for unsupported browsers at the bottom of this Readme
To use lzy.js include the script in your html file
<script src="lzy.js> </script>
Ensure all the elements you want lazily-loaded have a data-src attribute, with the path to the image you want to use.
<img data-src="path_to_image.jpg">This will resolve to
<img src="path_to_image.jpg">Or for any non img element it will resove to
<div style="background-image: url("path_to_image.jpg);"> </div>To trigger it, add the following function at the bottom of lzy.js, or in script that's loaded afterwards if you want more control.
lzy();To customise the offset value, call it like below. This scenario will load images as they get 500px from the viewport.
lzy({
offset: 500
});lzy.js uses the intersectionObserver API, which currently doesn't have an amazing amount of browser support. pollyfill.io to the rescue! To add support, add the following script to your html file, before lazy.js
<script> if (!window.IntersectionObserver) document.write('<script src="https://polyfill.io/v2/polyfill.min.js?features=IntersectionObserver"> <\/script>'); </script>