UNPKG

60.4 kBMarkdownView Raw
1LazyLoad is a lightweight (2.4 kB) and flexible script that **speeds up your web application** by deferring the loading of your below-the-fold images, animated SVGs, videos and iframes to **when they will enter the viewport**. It's written in plain "vanilla" JavaScript, it leverages the [IntersectionObserver](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API) API, it supports [responsive images](https://alistapart.com/article/responsive-images-in-practice), it optimizes your website for slower connections, and can enable native lazy loading. See [all features](#-all-features-compared) for more.
2
3[![vanilla-lazyload (latest)](https://img.shields.io/npm/v/vanilla-lazyload/latest.svg)](https://www.npmjs.com/package/vanilla-lazyload)
4[![vanilla-lazyload (downloads)](https://img.shields.io/npm/dy/vanilla-lazyload.svg)](https://www.npmjs.com/package/vanilla-lazyload)
5[![](https://data.jsdelivr.com/v1/package/npm/vanilla-lazyload/badge)](https://www.jsdelivr.com/package/npm/vanilla-lazyload)
6[![](https://github.com/verlok/vanilla-lazyload/actions/workflows/ci.yml/badge.svg)](https://github.com/verlok/vanilla-lazyload/actions/workflows/ci.yml)
7
8➡️ Jump to: [👨‍💻 Getting started - HTML](#-getting-started---html) - [👩‍💻 Getting started - Script](#-getting-started---script) - [🥧 Recipes](#-recipes) - [📺 Demos](#-demos) - [😋 Tips & tricks](#-tips--tricks) - [🔌 API](#-api) - [😯 All features compared](#-all-features-compared)
9
10---
11
12**Love this project? 😍 [Buy me a coffee!](https://ko-fi.com/verlok)**
13
14---
15
16## 👨‍💻 Getting started - HTML
17
18In order to make your content be loaded by LazyLoad, you must use some `data-` attributes instead of the actual attributes. Examples below.
19
20### Lazy image:
21
22```html
23<img alt="A lazy image" class="lazy" data-src="lazy.jpg" />
24```
25
26### Lazy image with low quality placeholder:
27
28```html
29<img alt="A lazy image" class="lazy" src="lazy-lowQuality.jpg" data-src="lazy.jpg" />
30```
31
32### Lazy responsive image with `srcset` and `sizes`:
33
34```html
35<img
36 alt="A lazy image"
37 class="lazy"
38 data-src="lazy.jpg"
39 data-srcset="lazy_400.jpg 400w,
40 lazy_800.jpg 800w"
41 data-sizes="100w"
42/>
43```
44
45To have a low quality placeholder, add the `src` attribute pointing to a very small version of the image. E.g. `src="lazy_10.jpg"`.
46
47### Lazy responsive image with hi-dpi support using the `picture` tag:
48
49```html
50<picture>
51 <source media="(min-width: 1200px)" data-srcset="lazy_1200.jpg 1x, lazy_2400.jpg 2x" />
52 <source media="(min-width: 800px)" data-srcset="lazy_800.jpg 1x, lazy_1600.jpg 2x" />
53 <img alt="A lazy image" class="lazy" data-src="lazy.jpg" />
54</picture>
55```
56
57To have a low quality placeholder, add the `src` attribute pointing to a very small version of the image to the `img` tag. E.g. `src="lazy_10.jpg"`.
58
59### Lazy responsive image with automatic _WebP_ format selection, using the `picture` tag:
60
61```html
62<picture>
63 <source
64 type="image/webp"
65 data-srcset="lazy_400.webp 400w,
66 lazy_800.webp 800w"
67 data-sizes="100w"
68 />
69 <img
70 alt="A lazy image"
71 class="lazy"
72 data-src="lazy.jpg"
73 data-srcset="lazy_400.jpg 400w,
74 lazy_800.jpg 800w"
75 data-sizes="100w"
76 />
77</picture>
78```
79
80To have a low quality placeholder, add the `src` attribute pointing to a very small version of the image to the `img` tag. E.g. `src="lazy_10.jpg"`.
81
82### Lazy background image
83
84**IMPORTANT NOTE**: To display content images on your pages, always use the `img` tag. This would benefit the SEO and the accessibility of your website. To understand if your images are content or background, ask yourself: "would my website user like to see those images when printing out the page?". If the answer is "yes", then your images are content images and you should avoid using background images to display them.
85
86#### Single background image:
87
88```html
89<div class="lazy" data-bg="lazy.jpg"></div>
90```
91
92#### Single background, with HiDPI screen support:
93
94```html
95<div class="lazy" data-bg="lazy.jpg" data-bg-hidpi="lazy@2x.jpg"></div>
96```
97
98#### Multiple backgrounds:
99
100```html
101<div
102 class="lazy"
103 data-bg-multi="url(lazy-head.jpg),
104 url(lazy-body.jpg),
105 linear-gradient(#fff, #ccc)"
106>
107 ...
108</div>
109```
110
111#### Multiple backgrounds, HiDPI screen support:
112
113```html
114<div
115 class="lazy"
116 data-bg-multi="url(lazy-head.jpg),
117 url(lazy-body.jpg),
118 linear-gradient(#fff, #ccc)"
119 data-bg-multi-hidpi="url(lazy-head@2x.jpg),
120 url(lazy-body@2x.jpg),
121 linear-gradient(#fff, #ccc)"
122>
123 ...
124</div>
125```
126
127#### Backgrounds with `image-set`:
128
129```html
130<div class="lazy" data-bg-set="url('lazy@1x.jpg') 1x, url('lazy@2x.jpg') 2x">...</div>
131```
132
133#### Multiple backgrounds with `image-set`:
134
135```html
136<div
137 class="lazy"
138 data-bg-set="
139 url('lazy-head@1x.jpg') 1x, url('lazy-head@2x.jpg') 2x |
140 url('lazy-body@1x.jpg') 1x, url('lazy-body@2x.jpg') 2x
141 "
142>
143 ...
144</div>
145```
146
147### Lazy animated SVG
148
149```html
150<object class="lazy" type="image/svg+xml" data-src="lazy.svg"></object>
151```
152
153### Lazy video
154
155```html
156<video class="lazy" controls width="620" data-src="lazy.mp4" data-poster="lazy.jpg">
157 <source type="video/mp4" data-src="lazy.mp4" />
158 <source type="video/ogg" data-src="lazy.ogg" />
159 <source type="video/avi" data-src="lazy.avi" />
160</video>
161```
162
163Please note that the video poster can be lazily loaded too.
164
165### Lazy iframe
166
167```html
168<iframe class="lazy" data-src="lazyFrame.html"></iframe>
169```
170
171---
172
173**Love this project? 😍 [Buy me a coffee!](https://ko-fi.com/verlok)**
174
175---
176
177## 👩‍💻 Getting started - Script
178
179The latest, recommended version of LazyLoad is **19.1.3**.
180Note that if you need to support Internet Explorer 11, you need to use version 17.9.0 or below.
181
182Quickly understand how to upgrade from a previous version reading the [practical upgrade guide](UPGRADE.md).
183
184### The simple, easiest way
185
186The easiest way to use LazyLoad is to include the script from a CDN.
187
188```html
189<script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload@19.1.3/dist/lazyload.min.js"></script>
190```
191
192OR, if you prefer to import it as an ES module:
193
194```html
195<script type="module">
196 import LazyLoad from 'https://cdn.jsdelivr.net/npm/vanilla-lazyload@19.0.3/+esm'
197</script>
198```
199
200Then, in your javascript code:
201
202```js
203var lazyLoadInstance = new LazyLoad({
204 // Your custom settings go here
205});
206```
207
208To be sure that DOM for your lazy content is ready when you instantiate LazyLoad, **place the script tag right before the closing `</body>` tag**.
209
210If more DOM arrives later, e.g. via an AJAX call, you'll need to call `lazyLoadInstance.update();` to make LazyLoad check the DOM again.
211
212```js
213lazyLoadInstance.update();
214```
215
216### Using an `async` script
217
218If you prefer, it's possible to include LazyLoad's script using `async` script and initialize it as soon as it's loaded.
219
220To do so, **you must define the options before including the script**. You can pass:
221
222- `{}` an object to get a single instance of LazyLoad
223- `[{}, {}]` an array of objects to get multiple instances of LazyLoad, each one with different options.
224
225```html
226<script>
227 // Set the options globally
228 // to make LazyLoad self-initialize
229 window.lazyLoadOptions = {
230 // Your custom settings go here
231 };
232</script>
233```
234
235Then include the script.
236
237```html
238<script
239 async
240 src="https://cdn.jsdelivr.net/npm/vanilla-lazyload@19.1.3/dist/lazyload.min.js"
241></script>
242```
243
244**Possibly place the script tag right before the closing `</body>` tag**. If you can't do that, LazyLoad could be executed before the browser has loaded all the DOM, and you'll need to call its `update()` method to make it check the DOM again.
245
246### Using an `async` script + getting the instance reference
247
248Same as above, but you must put the `addEventListener` code shown below before including the `async` script.
249
250```html
251<script>
252 // Set the options globally
253 // to make LazyLoad self-initialize
254 window.lazyLoadOptions = {
255 // Your custom settings go here
256 };
257 // Listen to the initialization event
258 // and get the instance of LazyLoad
259 window.addEventListener(
260 "LazyLoad::Initialized",
261 function (event) {
262 window.lazyLoadInstance = event.detail.instance;
263 },
264 false
265 );
266</script>
267```
268
269Then include the script.
270
271```html
272<script
273 async
274 src="https://cdn.jsdelivr.net/npm/vanilla-lazyload@19.1.3/dist/lazyload.min.js"
275></script>
276```
277
278Now you'll be able to call its methods, like:
279
280```js
281lazyLoadInstance.update();
282```
283
284[DEMO](https://verlok.github.io/vanilla-lazyload/demos/async.html) - [SOURCE](https://github.com/verlok/vanilla-lazyload/blob/master/demos/async.html) &larr; for a single LazyLoad instance
285
286[DEMO](https://verlok.github.io/vanilla-lazyload/demos/async_multiple.html) - [SOURCE](https://github.com/verlok/vanilla-lazyload/blob/master/demos/async_multiple.html) &larr; for multiple LazyLoad instances
287
288### Local install
289
290If you prefer to install LazyLoad locally in your project, you can!
291
292#### Using npm
293
294```
295npm install vanilla-lazyload
296```
297
298#### Using bower
299
300```
301bower install vanilla-lazyload
302```
303
304#### Manual download
305
306Download one the latest [releases](https://github.com/verlok/vanilla-lazyload/releases/). The files you need are inside the `dist` folder. If you don't know which one to pick, use `lazyload.min.js`, or read [about bundles](#bundles).
307
308### Local usage
309
310Should you install LazyLoad locally, you can import it as ES module like the following:
311
312```js
313import LazyLoad from "vanilla-lazyload";
314```
315
316It's also possible (but unadvised) to use the `require` commonJS syntax.
317
318More information about bundling LazyLoad with WebPack are available on [this specific repo](https://github.com/verlok/lazyload-es2015-webpack-test).
319
320### Usage with React
321
322Take a look at this example of [usage of React with LazyLoad](https://codesandbox.io/s/20306yk96p) on Sandbox.
323
324This implementation takes the same props that you would normally pass to the `img` tag, but it renders a lazy image. Feel free to fork and improve it!
325
326### Bundles
327
328Inside the `dist` folder you will find different bundles.
329
330| Filename | Module Type | Advantages |
331| ---------------------- | ------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
332| `lazyload.min.js` | UMD <small>(Universal Module Definition)</small> | Works pretty much everywhere, even in common-js contexts |
333| `lazyload.iife.min.js` | IIFE <small>(Immediately Invoked Function Expression)</small> | Works as in-page `<script src="...">`, ~0.5kb smaller than UMD version |
334| `esm/lazyload.js` | ES Module | Exports `LazyLoad` so you can import it in your project both using `<script type="module" src="...">` and a bundler like WebPack or Rollup |
335
336---
337
338**Love this project? 😍 [Buy me a coffee!](https://ko-fi.com/verlok)**
339
340---
341
342## 🥧 Recipes
343
344This is the section where you can find _ready to copy & paste_ code for your convenience.
345
346### Hide alt text and empty image
347
348> 💡 **Use case**: when your lazily loaded images show their `alt` text and the empty image icon before loading.
349
350CSS
351
352```css
353img:not([src]):not([srcset]) {
354 visibility: hidden;
355}
356```
357
358Just that, really.
359
360### Image errors handling
361
362> 💡 **Use case**: when you want to prevent showing unexisting/broken images on your website.
363
364Javascript
365
366```js
367var myLazyLoad = new LazyLoad({
368 // Other options here...
369 callback_error: (img) => {
370 // Use the following line only if your images have the `srcset` attribute
371 img.setAttribute("srcset", "fallback_image@1x.jpg 1x, fallback_image@2x.jpg 2x");
372 img.setAttribute("src", "fallback_image@1x.jpg");
373 }
374});
375```
376
377NOTE: if the error was generated by a network down (navigator if temporarily offline), vanilla-lazyload will try and load the images again when the network becomes available again.
378
379[EXAMPLE](https://codepen.io/verlok/pen/mdwYbGq) - [API](#-api)
380
381### Dynamic content
382
383> 💡 **Use case**: when you want to lazily load images, but the number of images change in the scrolling area changes, maybe because they are added asynchronously.
384
385Javascript
386
387```js
388var myLazyLoad = new LazyLoad();
389// After your content has changed...
390myLazyLoad.update();
391```
392
393[DEMO](https://verlok.github.io/vanilla-lazyload/demos/dynamic_content.html) - [SOURCE](https://github.com/verlok/vanilla-lazyload/blob/master/demos/dynamic_content.html) - [API](#-api)
394
395### Mixed native and JS-based lazy loading
396
397> 💡 **Use case**: you want to use the `use_native` option to delegate the loading of images, iframes and videos to the browsers engine where supported, but you also want to lazily load background images.
398
399HTML
400
401```html
402<img class="lazy" alt="A lazy image" data-src="lazy.jpg" />
403<iframe class="lazy" data-src="lazyFrame.html"></iframe>
404<video class="lazy" controls data-src="lazy.mp4" data-poster="lazy.jpg">...</video>
405<object class="lazy" type="image/svg+xml" data-src="lazy.svg"></object>
406<div class="lazy" data-bg="lazy.jpg"></div>
407```
408
409Javascript
410
411```js
412// Instance using native lazy loading
413const lazyContent = new LazyLoad({
414 use_native: true // <-- there you go
415});
416
417// Instance without native lazy loading
418const lazyBackground = new LazyLoad({
419 // DON'T PASS use_native: true HERE
420});
421```
422
423[DEMO](https://verlok.github.io/vanilla-lazyload/demos/native_lazyload_conditional.html) - [SOURCE](https://github.com/verlok/vanilla-lazyload/blob/master/demos/native_lazyload_conditional.html) - [API](#-api)
424
425### Scrolling panel(s)
426
427> 💡 **Use case**: when your scrolling container is not the main browser window, but a scrolling container.
428
429HTML
430
431```html
432<div class="scrollingPanel">
433 <!-- Set of images -->
434</div>
435```
436
437Javascript
438
439```js
440var myLazyLoad = new LazyLoad({
441 container: document.querySelector(".scrollingPanel")
442});
443```
444
445[DEMO](https://verlok.github.io/vanilla-lazyload/demos/container_single.html) - [SOURCE](https://github.com/verlok/vanilla-lazyload/blob/master/demos/container_single.html) - [API](#-api)
446
447If you have _multiple_ scrolling panels, you can use the following markup and code.
448
449HTML
450
451```html
452<div id="scrollingPanel1" class="scrollingPanel">
453 <!-- Set of images -->
454</div>
455<div id="scrollingPanel2" class="scrollingPanel">
456 <!-- Set of images -->
457</div>
458```
459
460Javascript
461
462```js
463var myLazyLoad1 = new LazyLoad({
464 container: document.getElementById("scrollingPanel1")
465});
466var myLazyLoad2 = new LazyLoad({
467 container: document.getElementById("scrollingPanel2")
468});
469```
470
471[DEMO](https://verlok.github.io/vanilla-lazyload/demos/container_multiple.html) - [SOURCE](https://github.com/verlok/vanilla-lazyload/blob/master/demos/container_multiple.html) - [API](#-api)
472
473### Lazy functions
474
475> 💡 **Use case**: when you want to execute arbitrary scripts or functions when given elements enter the viewport
476
477HTML
478
479```html
480<div class="lazy" data-lazy-function="foo">...</div>
481<div class="lazy" data-lazy-function="bar">...</div>
482<div class="lazy" data-lazy-function="buzz">...</div>
483<div class="lazy" data-lazy-function="booya">...</div>
484```
485
486JS
487
488```js
489// It's a best practice to scope the function names inside a namespace like `lazyFunctions`.
490window.lazyFunctions = {
491 foo: function (element) {
492 element.style.color = "red";
493 console.log("foo");
494 },
495 bar: function (element) {
496 element.remove(element);
497 console.log("bar");
498 },
499 buzz: function (element) {
500 var span = document.createElement("span");
501 span.innerText = " - buzz!";
502 element.appendChild(span);
503 console.log("buzz");
504 },
505 booya: function (element) {
506 element.classList.add("boo");
507 console.log("booya");
508 }
509};
510```
511
512```js
513function executeLazyFunction(element) {
514 var lazyFunctionName = element.getAttribute("data-lazy-function");
515 var lazyFunction = window.lazyFunctions[lazyFunctionName];
516 if (!lazyFunction) return;
517 lazyFunction(element);
518}
519
520var ll = new LazyLoad({
521 unobserve_entered: true, // <- Avoid executing the function multiple times
522 callback_enter: executeLazyFunction // Assigning the function defined above
523});
524```
525
526Use `unobserve_entered` to avoid executing the function multiple times.
527
528That's it. Whenever an element with the `data-lazy-function` attribute enters the viewport, LazyLoad calls the `executeLazyScript` function, which gets the function name from the `data-lazy-function` attribute itself and executes it.
529
530[DEMO](https://verlok.github.io/vanilla-lazyload/demos/lazy_functions.html) - [SOURCE](https://github.com/verlok/vanilla-lazyload/blob/master/demos/lazy_functions.html) - [API](#-api)
531
532### Lazy initialization of multiple LazyLoad instances
533
534> 💡 **Use case**: when you have a lot of horizontally scrolling containers and you want to instantiate a LazyLoad instance on them, but only when they entered the viewport.
535
536HTML
537
538```html
539<div class="horizContainer">
540 <img
541 src=""
542 alt="Row 01, col 01"
543 data-src="https://placeholdit.imgix.net/~text?txtsize=19&amp;txt=row_01_col_01&amp;w=200&amp;h=200"
544 />
545 <img
546 src=""
547 alt="Row 01, col 02"
548 data-src="https://placeholdit.imgix.net/~text?txtsize=19&amp;txt=row_01_col_02&amp;w=200&amp;h=200"
549 />
550 <!-- ... -->
551</div>
552<div class="horizContainer">
553 <img
554 src=""
555 alt="Row 02, col 01"
556 data-src="https://placeholdit.imgix.net/~text?txtsize=19&amp;txt=row_02_col_01&amp;w=200&amp;h=200"
557 />
558 <img
559 src=""
560 alt="Row 02, col 02"
561 data-src="https://placeholdit.imgix.net/~text?txtsize=19&amp;txt=row_02_col_02&amp;w=200&amp;h=200"
562 />
563 <!-- ... -->
564</div>
565```
566
567Javascript
568
569```js
570var lazyLoadInstances = [];
571
572var initOneLazyLoad = function (horizContainerElement) {
573 // When the .horizContainer element enters the viewport,
574 // instantiate a new LazyLoad on the horizContainerElement
575 var oneLL = new LazyLoad({
576 container: horizContainerElement
577 });
578 // Optionally push it in the lazyLoadInstances
579 // array to keep track of the instances
580 lazyLoadInstances.push(oneLL);
581};
582
583// The "lazyLazy" instance of lazyload is used to check
584// when the .horizContainer divs enter the viewport
585var lazyLazy = new LazyLoad({
586 elements_selector: ".horizContainer",
587 callback_enter: initOneLazyLoad,
588 unobserve_entered: true // Stop observing .horizContainer(s) after they entered
589});
590```
591
592That's it. Whenever a `.horizContainer` element enters the viewport, LazyLoad calls the `initOneLazyLoad` function, which creates a new instance of LazyLoad on the `.horizContainer` element.
593
594[DEMO](https://verlok.github.io/vanilla-lazyload/demos/lazily_load_lazyLoad.html) - [SOURCE](https://github.com/verlok/vanilla-lazyload/blob/master/demos/lazily_load_lazyLoad.html) - [API](#-api)
595
596---
597
598**Love this project? 😍 [Buy me a coffee!](https://ko-fi.com/verlok)**
599
600---
601
602## 📺 Demos
603
604Didn't find the [recipe](#-recipes) that exactly matches your case? We have demos!
605
606The [demos](https://github.com/verlok/vanilla-lazyload/tree/master/demos) folder contains 30+ use cases of vanilla-lazyload. You might find there what you're looking for.
607
608| Type | Title | Code | Demo |
609| --------- | ---------------------------------------------------------------------------------------------- | ---------------------------------------------- | ---------------------------------------------------------------------------------------------- |
610| Content | Simple lazy loaded images, not using any placeholder | [Code](demos/image_basic.html) | [Live](https://verlok.github.io/vanilla-lazyload/demos/image_basic.html) |
611| Content | Lazy images that use an inline SVG as a placeholder | [Code](demos/image_ph_inline.html) | [Live](https://verlok.github.io/vanilla-lazyload/demos/image_ph_inline.html) |
612| Content | Lazy images that use an external SVG file as a placeholder | [Code](demos/image_ph_external.html) | [Live](https://verlok.github.io/vanilla-lazyload/demos/image_ph_external.html) |
613| Content | Lazy responsive images with `srcset` | [Code](demos/image_srcset.html) | [Live](https://verlok.github.io/vanilla-lazyload/demos/image_srcset.html) |
614| Content | Lazy responsive images with the `<picture>` tag and the `media` attribute (art direction) | [Code](demos/picture_media.html) | [Live](https://verlok.github.io/vanilla-lazyload/demos/picture_media.html) |
615| Content | Lazy responsive images with `srcset` and `sizes` (using `data-sizes`) | [Code](demos/image_srcset_lazy_sizes.html) | [Live](https://verlok.github.io/vanilla-lazyload/demos/image_srcset_lazy_sizes.html) |
616| Content | Lazy responsive images with `srcset` and `sizes` (using plain `sizes`) | [Code](demos/image_srcset_sizes.html) | [Live](https://verlok.github.io/vanilla-lazyload/demos/image_srcset_sizes.html) |
617| Content | Lazy video with multiple `<source>` tags, different preload options, NO autoplay | [Code](demos/video.html) | [Live](https://verlok.github.io/vanilla-lazyload/demos/video.html) |
618| Content | Lazy video with multiple `<source>` tags, different preload options, WITH autoplay | [Code](demos/video_autoplay.html) | [Live](https://verlok.github.io/vanilla-lazyload/demos/video_autoplay.html) |
619| Content | Lazy loading background images | [Code](demos/background_images.html) | [Live](https://verlok.github.io/vanilla-lazyload/demos/background_images.html) |
620| Content | Lazy loading multiple background images | [Code](demos/background_images_multi.html) | [Live](https://verlok.github.io/vanilla-lazyload/demos/background_images_multi.html) |
621| Content | Lazy loading background images with `image-set()` | [Code](demos/background_images_image-set.html) | [Live](https://verlok.github.io/vanilla-lazyload/demos/background_images_image-set.html) |
622| Content | Lazy loading iframes | [Code](demos/iframes.html) | [Live](https://verlok.github.io/vanilla-lazyload/demos/iframes.html) |
623| Content | Lazy loading animated SVGs and PDF files | [Code](demos/objects.html) | [Live](https://verlok.github.io/vanilla-lazyload/demos/objects.html) |
624| Content | Lazy WebP images with the `<picture>` tag and the `type` attribute for WebP | [Code](demos/picture_type_webp.html) | [Live](https://verlok.github.io/vanilla-lazyload/demos/picture_type_webp.html) |
625| Loading | Asynchronous loading LazyLoad with `<script async>` | [Code](demos/async.html) | [Live](https://verlok.github.io/vanilla-lazyload/demos/async.html) |
626| Loading | Asynchronous loading multiple LazyLoad instances with `<script async>` | [Code](demos/async_multiple.html) | [Live](https://verlok.github.io/vanilla-lazyload/demos/async_multiple.html) |
627| Error | Test error loading behaviour when `restore_on_error` is `false` | [Code](demos/error_no_restore.html) | [Live](https://verlok.github.io/vanilla-lazyload/demos/error_no_restore.html) |
628| Error | Test error loading behaviour when `restore_on_error` is `true` | [Code](demos/error_restore.html) | [Live](https://verlok.github.io/vanilla-lazyload/demos/error_restore.html) |
629| Technique | Fade in images as they load | [Code](demos/fade_in.html) | [Live](https://verlok.github.io/vanilla-lazyload/demos/fade_in.html) |
630| Technique | Lazy load images in CSS-only horizontal sliders (Netflix style) | [Code](demos/sliders_css_only.html) | [Live](https://verlok.github.io/vanilla-lazyload/demos/sliders_css_only.html) |
631| Technique | Lazily create Swiper instances and lazily load Swiper images | [Code](demos/swiper.html) | [Live](https://verlok.github.io/vanilla-lazyload/demos/swiper.html) |
632| Technique | Lazily execute functions as specific elements enter the viewport | [Code](demos/lazy_functions.html) | [Live](https://verlok.github.io/vanilla-lazyload/demos/lazy_functions.html) |
633| Technique | How to manage the print of a page with lazy images | [Code](demos/print.html) | [Live](https://verlok.github.io/vanilla-lazyload/demos/print.html) |
634| Technique | A popup layer containing lazy images in a scrolling container | [Code](demos/popup_layer.html) | [Live](https://verlok.github.io/vanilla-lazyload/demos/popup_layer.html) |
635| Settings | Multiple scrolling containers | [Code](demos/container_multiple.html) | [Live](https://verlok.github.io/vanilla-lazyload/demos/container_multiple.html) |
636| Settings | Single scrolling container | [Code](demos/container_single.html) | [Live](https://verlok.github.io/vanilla-lazyload/demos/container_single.html) |
637| Methods | How to `restore()` DOM to its original state, and/or `destroy()` LazyLoad | [Code](demos/restore_destroy.html) | [Live](https://verlok.github.io/vanilla-lazyload/demos/restore_destroy.html) |
638| Methods | Adding dynamic content, then `update()` LazyLoad | [Code](demos/dynamic_content.html) | [Live](https://verlok.github.io/vanilla-lazyload/demos/dynamic_content.html) |
639| Methods | Adding dynamic content, then `update()` LazyLoad passing a NodeSet of elements | [Code](demos/dynamic_content_nodeset.html) | [Live](https://verlok.github.io/vanilla-lazyload/demos/dynamic_content_nodeset.html) |
640| Methods | Load punctual images using the `load()` method | [Code](demos/load.html) | [Live](https://verlok.github.io/vanilla-lazyload/demos/load.html) |
641| Methods | Load all images at once using `loadAll()` | [Code](demos/load_all.html) | [Live](https://verlok.github.io/vanilla-lazyload/demos/load_all.html) |
642| Test | Test for multiple thresholds | [Code](demos/thresholds.html) | [Live](https://verlok.github.io/vanilla-lazyload/demos/thresholds.html) |
643| Test | Test behaviour with hidden images | [Code](demos/image_hidden.html) | [Live](https://verlok.github.io/vanilla-lazyload/demos/image_hidden.html) |
644| Test | Test performance, lazy loading of hundreds of images | [Code](demos/hundreds.html) | [Live](https://verlok.github.io/vanilla-lazyload/demos/hundreds.html) |
645| Native | Test the native lazy loading of images _WITHOUT_ any line of javascript, not even this script | [Code](demos/native_lazyload.html) | [Live](https://verlok.github.io/vanilla-lazyload/demos/native_lazyload.html) |
646| Native | Test the native lazy loading of images _conditionally_ using the `use_native` option (see API) | [Code](demos/native_lazyload_conditional.html) | [Live](https://verlok.github.io/vanilla-lazyload/demos/native_lazyload_conditional.html) |
647
648---
649
650**Love this project? 😍 [Buy me a coffee!](https://ko-fi.com/verlok)**
651
652---
653
654## 😋 Tips & tricks
655
656### Minimize [CLS](https://web.dev/cls) by occupy space beforehand
657
658It's very important to make sure that your lazy images occupy some space even **before they are loaded**, otherwise the `img` elements will be shrinked to zero-height, causing your layout to shift and making lazyload inefficient.
659
660The best way to do that is to set both `width` and `height` attributes to `img` and `video` elements and, if you choose not to use a placeholder image, apply the `display: block` CSS rule to every image.
661
662You can find more details and demos in my article [aspect-ratio: A modern way to reserve space for images and async content in responsive design](https://www.andreaverlicchi.eu/blog/aspect-ratio-modern-reserve-space-lazy-images-async-content-responsive-design/).
663
664---
665
666**Love this project? 😍 [Buy me a coffee!](https://ko-fi.com/verlok)**
667
668---
669
670## 🔌 API
671
672### Constructor arguments
673
674The `new LazyLoad()` instruction you execute on your page can take two parameters:
675
676| Parameter | What to pass | Required | Default value | Type |
677| --------- | ----------------------------------------------- | -------- | ------------- | ------------ |
678| Options | The option object for this instance of LazyLoad | No | `{}` | Plain Object |
679| Nodeset | A NodeSet of elements to execute LazyLoad on | No | `null` | NodeSet |
680
681The most common usage of LazyLoad constructor is to pass only the options object (see "options" in the next section). For example:
682
683```js
684var aLazyLoad = new LazyLoad({
685 /* options here */
686});
687```
688
689In the unusual cases when you can't select the elements using `elements_selector`, you could pass the elements set as a second parameter. It can be either a NodeSet or an array of DOM elements.
690
691```js
692var elementsToLazyLoad = getElementSetFromSomewhere();
693var aLazyLoad = new LazyLoad(
694 {
695 /* options here */
696 },
697 elementsToLazyLoad
698);
699```
700
701### Options
702
703For every instance of _LazyLoad_ you can pass in some options, to alter its default behaviour.
704Here's the list of the options.
705
706| Name | Meaning | Default value | Example value |
707| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------ | ---------------------------------------- |
708| `container` | The scrolling container of the elements in the `elements_selector` option. | `document` | `document.querySelector('.scrollPanel')` |
709| `elements_selector` | The CSS selector of the elements to load lazily, which will be selected as descendants of the `container` object. | `".lazy"` | `".lazyload"` |
710| `threshold` | A number of pixels representing the outer distance off the scrolling area from which to start loading the elements. | `300` | `0` |
711| `thresholds` | Similar to `threshold`, but accepting multiple values and both `px` and `%` units. It maps directly to the `rootMargin` property of IntersectionObserver ([read more](https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver/rootMargin)), 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%"` |
712| `data_src` | The 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"` |
713| `data_srcset` | The 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"` |
714| `data_sizes` | The 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"` |
715| `data_bg` | The 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"` |
716| `data_bg_hidpi` | The 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"` |
717| `data_bg_multi` | The 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"` |
718| `data_bg_multi_hidpi` | The 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"` |
719| `data_bg_set` | The name of the data attribute containing the value of the background to be applied with image-set, excluding the `"data-"` part. E.g. if your data attribute is named `"data-bg-set"`, just pass `"bg-set"`. The attribute value must be what goes inside the `image-set` CSS function. You can separate values with a pipe (`\|`) character to have multiple backgrounds. | `"bg-set"` | `"lazy-bg-set"` |
720| `data_poster` | The 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"` |
721| `class_applied` | The class applied to the multiple background elements after the multiple background was applied | `"applied"` | `"lazy-applied"` |
722| `class_loading` | The class applied to the elements while the loading is in progress. | `"loading"` | `"lazy-loading"` |
723| `class_loaded` | The class applied to the elements when the loading is complete. | `"loaded"` | `"lazy-loaded"` |
724| `class_error` | The class applied to the elements when the element causes an error. | `"error"` | `"lazy-error"` |
725| `class_entered` | The class applied to the elements after they entered the viewport. | `"entered"` | `"lazy-entered"` |
726| `class_exited` | The 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"` |
727| `cancel_on_exit` | A 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, `iframe`s, `object`s nor `video`s. | `true` | `false` |
728| `unobserve_entered` | A boolean that defines whether or not to automatically unobserve elements once they entered the viewport | `false` | `true` |
729| `unobserve_completed` | A boolean that defines whether or not to automatically unobserve elements once they've loaded or throwed an error | `true` | `false` |
730| `callback_enter` | A 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)}` |
731| `callback_exit` | A 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)}` |
732| `callback_loading` | A callback function which is called whenever an element starts loading. Arguments: DOM element, lazyload instance. | `null` | `(el)=>{console.log("Loading", el)}` |
733| `callback_cancel` | A 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)}` |
734| `callback_loaded` | A 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)}` |
735| `callback_error` | A callback function which is called whenever an element triggers an error. Arguments: DOM element, lazyload instance. | `null` | `(el)=>{console.log("Error", el)}` |
736| `callback_applied` | A callback function which is called whenever a multiple background element starts loading. Arguments: DOM element, lazyload instance. | `null` | `(el)=>{console.log("Applied", el)}` |
737| `callback_finish` | A 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")}` |
738| `use_native` | This boolean sets whether or not to use [native lazy loading](https://addyosmani.com/blog/lazy-loading/) to do [hybrid lazy loading](https://www.smashingmagazine.com/2019/05/hybrid-lazy-loading-progressive-migration-native/). On browsers that support it, LazyLoad will set the `loading="lazy"` attribute on images, iframes and videos, and delegate their loading to the browser. | `false` | `true` |
739| `restore_on_error` | Tells LazyLoad if to restore the original values of `src`, `srcset` and `sizes` when a loading error occurs. | `false` | `true` |
740
741### Methods
742
743**Instance methods**
744
745You can call the following methods on any instance of LazyLoad.
746
747| Method name | Effect | Use case |
748| -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- |
749| `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. |
750| `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 |
751| `restoreAll()` | Restores DOM to its original state. Note that it doesn't destroy LazyLoad, so you probably want to use it along with `destroy()`. | Reset the DOM before a soft page navigation (SPA) occures, e.g. using TurboLinks. |
752| `destroy()` | Destroys the instance, unsetting instance variables and removing listeners. | Free up some memory. Especially useful for Single Page Applications. |
753
754**Static methods**
755
756You can call the following static methods on the LazyLoad class itself (e.g. `LazyLoad.load(element, settings)`).
757
758| Method name | Effect | Use case |
759| ------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
760| `load(element, settings)` | Immediately loads the lazy `element`. You can pass your custom options in the `settings` parameter. Note that the `elements_selector` option has no effect, since you are passing the element as a parameter. Also note that this method has effect only once on a specific `element`. | To load an `element` at mouseover or at any other event different than "entering the viewport" |
761| `resetStatus(element)` | Resets the internal status of the given `element`. | To tell LazyLoad to consider this `element` again, for example: if you changed the `data-src` attribute after the previous `data-src` was loaded, call this method, then call `update()` on the LazyLoad instance. |
762
763### Properties
764
765You can use the following properties on any instance of LazyLoad.
766
767| Property name | Value |
768| -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
769| `loadingCount` | The 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. |
770| `toLoadCount` | The number of elements that haven't been lazyloaded yet (limitedly to the ones managed by the instance of LazyLoad) |
771
772---
773
774**Love this project? 😍 [Buy me a coffee!](https://ko-fi.com/verlok)**
775
776---
777
778## 😯 All features, compared
779
780A list of all vanilla-lazyload features, compared with other popular lazy loading libraries.
781
782### vanilla-lazyload VS lazysizes
783
784| It | vanilla-lazyload | lazysizes |
785| ---------------------------------------------------------------------------------------- | ---------------- | ----------- |
786| Is lightweight | ✔ (2.8 kB) | ✔ (3.4 kB) |
787| Is extendable | ✔ (API) | ✔ (plugins) |
788| Is SEO friendly | ✔ | ✔ |
789| Optimizes performance by cancelling downloads of images that already exited the viewport | ✔ | |
790| Retries loading after network connection went off and on again | ✔ | |
791| Supports conditional usage of native lazyloading | ✔ | |
792| Works with your DOM, your own classes and data-attributes | ✔ | |
793| Can lazyload responsive images | ✔ | ✔ |
794| ...and automatically calculate the value of the `sizes` attribute | | ✔ |
795| Can lazyload iframes | ✔ | ✔ |
796| Can lazyload animated SVGs | ✔ | |
797| Can lazyload videos | ✔ | |
798| Can lazyload background images | ✔ | |
799| Can lazily execute code, when given elements enter the viewport | ✔ | |
800| Can restore DOM to its original state | ✔ | |
801
802Weights source: [bundlephobia](https://bundlephobia.com/). Find others table rows explanation below.
803
804#### Is extendable
805
806Both scripts are extendable, check out the [API](#-api).
807
808#### Is SEO friendly
809
810Both scripts **don't hide images/assets from search engines**. No matter what markup pattern you use. Search engines don't scroll/interact with your website. These scripts detects whether or not the user agent is capable to scroll. If not, they reveal all images instantly.
811
812#### Optimizes performance by cancelling downloads of images that already exited the viewport
813
814If your mobile users are on slow connections and scrolls down fast, vanilla-lazyload cancels the download of images that are still loading but already exited the viewport.
815
816#### Retries loading after network connection went off and on
817
818If your mobile users are on flaky connections and go offline and back online, vanilla-lazyload retries downloading the images that errored.
819
820#### Supports conditional usage of native lazyloading
821
822If your users are on a browser supporting native lazyloading and you want to use it, just set the `use_native` option to `true`.
823
824#### Works with your DOM, your own classes and data-attributes
825
826Both scripts work by default with the `data-src` attribute and the `lazy` class in your DOM, but on LazyLoad you can change it, e.g. using `data-origin` to migrate from other lazy loading script.
827
828#### Can lazyload responsive images
829
830Both scripts can lazyload images and responsive images by all kinds, e.g. `<img src="..." srcset="..." sizes="...">` and `<picture><source media="..." srcset="" ...><img ...></picture>`.
831
832#### ...and automatically calculate the value of the `sizes` attribute
833
834lazysizes is it can derive the value of the `sizes` attribute from your CSS by using Javascript.
835vanilla-lazyload doesn't have this feature because of performance optimization reasons (the `sizes` attribute is useful to eagerly load responsive images when it's expressed in the markup, not when it's set by javascript).
836
837#### Can lazyload iframes
838
839Both scripts can lazyload the `iframe` tag.
840
841#### Can lazyload animated SVGs
842
843Only vanilla-lazyload can load animated SVGs via the `object` tag.
844
845#### Can lazyload videos
846
847Only vanilla-lazyload can lazyload the `video` tag, even with multiple `source`s.
848
849#### Can lazyload background images
850
851Only vanilla-lazyload can lazyload background images. And also multiple background images. And supporting HiDPI such as Retina and Super Retina display.
852
853#### Can lazily execute code, when given elements enter the viewport
854
855Check out the [lazy functions](#lazy-functions) section and learn how to execute code only when given elements enter the viewport.
856
857#### Can restore DOM to its original state
858
859Using the `restoreAll()` method, you can make LazyLoad restore all DOM manipulated from LazyLoad to how it was when the page was loaded the first time.
860
861---
862
863**Love this project? 😍 [Buy me a coffee!](https://ko-fi.com/verlok)**
864
865---
866
867## Tested on real browsers
868
869This script is tested in every browser before every release using [BrowserStack](http://browserstack.com/) live, thanks to the BrowserStack Open Source initiative.
870
871<a href="http://browserstack.com/"><img alt="BrowserStack Logo" src="./img/browserstack-logo-600x315.png" width="300" height="158"/></a>