vanilla-lazyload

repository·master·Indexed 27 days ago

https://github.com/verlok/vanilla-lazyload

A lightweight (2.4 kB) vanilla JavaScript library that improves web performance by deferring the loading of images, videos, iframes, and background images until they enter the viewport. It leverages the IntersectionObserver API and supports responsive images, native lazy loading, and custom function execution via data attributes. Version 19.1.3.

Tokens
5.9K
Snippets
17
Records
29
Agent score
43%

What's inside vanilla-lazyload

  1. Compare vanilla-lazyload features

    master

    vanilla-lazyload is a lightweight (2.8 kB) and flexible library that offers several performance-oriented features compared to other libraries like lazysizes.

    Key advantages include:

    • Optimized for INP: Uses IntersectionObserver.
    • Download Cancellation: Cancels downloads of images that have already exited the viewport.
    • Network Resilience: Retries loading images after a network connection is restored.
    • Native Lazyloading Support: Can be configured to use native browser lazyloading via the use_native option.
    • Extended Media Support: Supports lazyloading animated SVGs (via object tag), videos (including multiple <source> tags), and background images (including HiDPI/Retina support).
    • Code Execution: Can lazily execute code when elements enter the viewport.
    • DOM Restoration: Can restore the DOM to its original state using the restoreAll() method.
  2. Migrate from Version 12 to 13

    master

    When upgrading from version 12 to 13, replace callback_set with callback_reveal. While callback_set may still work temporarily, it is deprecated and scheduled for removal.

    // FROM
    new LazyLoad({ /* other options? */ callback_set: () => {} });
    // TO
    new LazyLoad({ /* other options? */ callback_reveal: () => {} });
  3. Minimize CLS (Cumulative Layout Shift) when using lazy loading

    master

    To prevent layout shifts (CLS) when images or videos load, ensure they occupy space before they are loaded. If elements shrink to zero-height before loading, the layout will shift, making lazy loading inefficient.

    Best Practices:

    1. Set both width and height attributes on img and video elements.
    2. If not using a placeholder image, apply display: block to every image via CSS.
  4. Lazy load background images

    master

    To lazy load background images on elements like <div>, use the following data- attributes:

    • data-bg: For a single background image.
    • data-bg-hidpi: For HiDPI/Retina support.
    • data-bg-multi: For multiple background images (comma-separated).
    • data-bg-multi-hidpi: For multiple backgrounds with HiDPI support.
    • data-bg-set: For using the CSS image-set() pattern.

    Note: For SEO and accessibility, prefer using <img> tags for content images instead of background images.

  5. Migrate from Version 15 to 16

    master

    When upgrading from version 15 to 16, apply the following changes:

    Replace callback_reveal

    Replace the callback_reveal callback with callback_loading.

    Update load(element) method usage

    The instance method load(element) has been replaced by a static method LazyLoad.load(element, settings). Note that the settings object can differ from your instance settings; if none are provided, defaults apply.

    // FROM
    myLazyLoad.load(element);
    
    // TO
    LazyLoad.load(element, {
      /* options here */
    });

    Replace auto_unobserve

    Replace the auto_unobserve option with unobserve_completed.

    const myLazyLoad = new LazyLoad({
      // FROM
      auto_unobserve: false,
      // TO
      unobserve_completed: false
    });

    Replace load_delay

    Replace load_delay: ___ with cancel_on_exit: true.

    LazyLoad.load(element, {
      /* options here */
    });
  6. Lazy load videos, iframes, and SVGs

    master

    LazyLoad supports various media types using specific data- attributes:

    • Animated SVGs: Use the <object> tag with data-src.
    • Videos: Use the <video> tag. You can lazy load the video source via <source data-src="..."> and the poster via data-poster="...".
    • Iframes: Use the <iframe> tag with data-src.
    <!-- Animated SVG -->
    <object class="lazy" type="image/svg+xml" data-src="lazy.svg"></object>
    
    <!-- Video -->
    <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" />
    </video>
    
    <!-- Iframe -->
    <iframe class="lazy" data-src="lazyFrame.html"></iframe>
  7. Lazy initialize LazyLoad instances

    master

    To optimize performance when dealing with many large containers (like horizontal scrolling rows), you can use a 'master' LazyLoad instance to observe the containers themselves. When a container enters the viewport, the callback_enter trigger can then instantiate a new LazyLoad instance specifically for that container.

    var lazyLoadInstances = [];
    
    var initOneLazyLoad = function (horizContainerElement) {
      var oneLL = new LazyLoad({
        container: horizContainerElement
      });
      lazyLoadInstances.push(oneLL);
    };
    
    // The 'master' instance observing the containers
    var lazyLazy = new LazyLoad({
      elements_selector: ".horizContainer",
      callback_enter: initOneLazyLoad,
      unobserve_entered: true // Stop observing the container after it is initialized
    });
  8. Lazy load images using HTML data attributes

    master

    To enable lazy loading for images, use the lazy class and replace standard attributes with data- attributes.

    Basic Lazy Image

    Use data-src instead of src.

    Lazy Image with Low Quality Placeholder

    Provide a small, lightweight image in the src attribute to act as a placeholder while the main image loads via data-src.

    Responsive Images

    Use data-srcset and data-sizes for responsive image support.

    Responsive Images with <picture> tag

    For advanced responsive images or HiDPI support, use the <picture> tag. Apply data-srcset to <source> elements and data-src to the <img> element.

    <!-- Basic -->
    <img alt="A lazy image" class="lazy" data-src="lazy.jpg" />
    
    <!-- With Placeholder -->
    <img alt="A lazy image" class="lazy" src="lazy-lowQuality.jpg" data-src="lazy.jpg" />
    
    <!-- Responsive -->
    <img
      alt="A lazy image"
      class="lazy"
      data-src="lazy.jpg"
      data-srcset="lazy_400.jpg 400w, 
        lazy_800.jpg 800w"
      data-sizes="100w"
    />
    
    <!-- Picture Tag -->
    <picture>
      <source media="(min-width: 1200px)" data-srcset="lazy_1200.jpg 1x, lazy_2400.jpg 2x" />
      <source media="(min-width: 800px)" data-srcset="lazy_800.jpg 1x, lazy_1600.jpg 2x" />
      <img alt="A lazy image" class="lazy" data-src="lazy.jpg" />
    </picture>
  9. Migrate from Version 13 to 14

    master

    When upgrading from version 13 to 14, replace callback_reveal with callback_loading. While callback_reveal may still work temporarily, it is deprecated and scheduled for removal.

    // FROM
    new LazyLoad({ /* other options? */ callback_reveal: () => {} });
    // TO
    new LazyLoad({ /* other options? */ callback_loading: () => {} });
  10. Execute custom functions using `data-lazy-function`

    master

    You can trigger arbitrary JavaScript functions when an element enters the viewport by using the data-lazy-function attribute.

    1. Define your functions in a namespace (e.g., window.lazyFunctions).
    2. Assign a function to the callback_enter option in the LazyLoad constructor.
    3. Use unobserve_entered: true to ensure the function only executes once per element.
    <div class="lazy" data-lazy-function="foo">...</div>
    window.lazyFunctions = {
      foo: function (element) {
        element.style.color = "red";
        console.log("foo");
      }
    };
    
    function executeLazyFunction(element) {
      var lazyFunctionName = element.getAttribute("data-lazy-function");
      var lazyFunction = window.lazyFunctions[lazyFunctionName];
      if (!lazyFunction) return;
      lazyFunction(element);
    }
    
    var ll = new LazyLoad({
      unobserve_entered: true, // Avoid executing the function multiple times
      callback_enter: executeLazyFunction
    });
  11. Migrate from Version 16 to 17

    master

    When upgrading from version 16 to 17, follow these steps depending on your current implementation:

    Target elements for lazy loading

    If you were not previously setting the elements_selector option, you must now add the lazy class to your lazy images:

    <!-- FROM -->
    <img data-src="lazyImage.jpg" alt="Lazy image" />
    <!-- TO -->
    <img class="lazy" data-src="lazyImage.jpg" alt="Lazy image" />

    Alternatively, you can configure the library to target all img tags by setting the elements_selector option:

    const myLazyLoad = new LazyLoad({
      /* other options here */
      elements_selector: "img"
    });

    Remove cancel_on_exit

    If you were using the cancel_on_exit: true option, you must remove it from your settings.

  12. Explore vanilla-lazyload use cases and demos

    master

    The project provides over 30 demos covering various use cases, including:

    • Content Types: Basic images, images with inline/external SVG placeholders, responsive images (srcset, sizes, <picture> tag), background images (including image-set()), videos (with/without autoplay), iframes, and animated SVGs/PDFs.
    • Loading Techniques: Asynchronous loading with <script async>, native lazy loading (conditional via use_native), and fading in images.
    • Advanced Techniques: Lazy loading in CSS-only sliders, integrating with Swiper, executing functions when elements enter the viewport, and managing print layouts.
    • API Methods: Using restore(), destroy(), update(), load(), and loadAll().
    • Settings: Handling multiple or single scrolling containers.

    You can find the source code for these demos in the demos folder of the repository.