Lazy Loading

> (World Wide) Web - (W3|WWW) > Web - Browser

Table of Contents

1 - About

When someone first goes to a page, we only load the resource (image, advertisements) that are visible in the web browser, before scrolling.

Historically, solutions for detecting if an element is visible in the viewport (in order to lazy-load its content) have been error-prone, often causing the browser to become sluggish.

Solutions have often listened for scroll or resize events, then used DOM APIs like getBoundingClientRect() to calculate where elements are relative to the viewport. This works, but is not efficient.

IntersectionObserver is a browser API that allows us to efficiently detect when an observed element enters or exits the browser's viewport.

Lazy loading is technique that defers loading of non-critical resources at page load time. Instead, these non-critical resources are loaded at the moment of need. Where images are concerned, “non-critical” is often synonymous with “off-screen”.

Learn more:

Library for image and video:

For Ads:

Example from Lazy Loading Images and Video

<img class="lazy" src="placeholder-image.jpg" data-src="image-to-lazy-load-1x.jpg" data-srcset="image-to-lazy-load-2x.jpg 2x, image-to-lazy-load-1x.jpg 1x" alt="I'm an image!">
document.addEventListener("DOMContentLoaded", function() {
  var lazyImages = []"img.lazy"));
  if ("IntersectionObserver" in window) {
    let lazyImageObserver = new IntersectionObserver(function(entries, observer) {
      entries.forEach(function(entry) {
        if (entry.isIntersecting) {
          let lazyImage =;
          lazyImage.src = lazyImage.dataset.src;
          lazyImage.srcset = lazyImage.dataset.srcset;
    lazyImages.forEach(function(lazyImage) {
  } else {
    // Possibly fall back to a more compatible method here

More …

2 - Library

web/browser/lazy_loading.txt · Last modified: 2019/03/23 20:27 by gerardnico