gitmyhub

lozad.js

JavaScript ★ 7.5k updated 7mo ago

🔥 Highly performant, light ~1kb and configurable lazy loader in pure JS with no dependencies for responsive images, iframes and more

A tiny, zero-dependency JavaScript library that uses the browser's built-in Intersection Observer to lazy-load images, videos, and iframes only when they scroll into view.

JavaScriptsetup: easycomplexity 1/5

Lozad.js is a small JavaScript library that delays loading images, videos, iframes, and other page elements until they are about to appear on the screen. This technique is called lazy loading, and it speeds up a webpage by avoiding the download of content the visitor has not yet scrolled to. On a long page with many images, this can significantly reduce initial load time and save bandwidth.

Most older lazy loading libraries work by listening to the scroll event and repeatedly checking whether each element is close to the visible area. This approach has a performance cost because it forces the browser to measure the position of every tracked element on each scroll event, which can make the page feel sluggish. Lozad.js takes a different approach: it uses the browser's Intersection Observer API, which was designed specifically for this purpose. The browser does the work of noticing when an element enters the viewport, and Lozad.js responds to that notification instead of polling constantly.

Using the library is straightforward. You add a class to any element you want to lazy load and store the real URL in a data attribute instead of the normal source attribute. Then you create a Lozad observer with a couple of lines of JavaScript and call its observe method. From that point on, elements are loaded automatically as the user scrolls toward them.

The library supports images, responsive images with multiple size variants, iframes, videos, audio elements, background images, and multiple background images on a single element. It also works with elements added to the page dynamically after the initial load, and it can be customized with options for how close to the viewport an element needs to be before loading begins.

Lozad.js has no dependencies, weighs about one kilobyte compressed, and is used in production by companies including Tesla, Binance, and Verizon. It is free and open source.

Where it fits