Convert Figma logo to code with AI

malchata logoyall.js

A fast, flexible, and small SEO-friendly lazy loader.

1,366
140
1,366
5

Top Related Projects

17,454

High performance and SEO friendly lazy loader for images (responsive and normal), iframes and more, that detects any visibility changes triggered through user interaction, CSS or JavaScript without configuration.

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

LazyLoad is a lightweight, flexible script that speeds up your website by deferring the loading of your below-the-fold images, backgrounds, videos, iframes and scripts to when they will enter the viewport. Written in plain "vanilla" JavaScript, it leverages IntersectionObserver, supports responsive images and enables native lazy loading.

Vanilla JavaScript plugin for lazyloading images

Lazy load your component, image or anything matters the performance.

Quick Overview

yall.js (Yet Another Lazy Loader) is a lightweight JavaScript library for lazy loading images and videos on web pages. It uses Intersection Observer API for modern browsers and falls back to event-based lazy loading for older browsers, providing a fast and efficient solution for optimizing page load times.

Pros

  • Small footprint (1.5 KB minified and gzipped)
  • Supports both images and videos
  • Uses Intersection Observer API for better performance
  • Provides fallback for older browsers

Cons

  • Limited customization options compared to some larger lazy loading libraries
  • Requires additional setup for responsive images
  • May not be suitable for complex lazy loading scenarios

Code Examples

  1. Basic usage for lazy loading images:
document.addEventListener("DOMContentLoaded", yall);
  1. Lazy loading with custom options:
document.addEventListener("DOMContentLoaded", function() {
  yall({
    observeChanges: true,
    threshold: 300
  });
});
  1. Lazy loading videos:
<video class="lazy" data-src="video.mp4" data-poster="poster.jpg">
  <source type="video/mp4" data-src="video.mp4">
</video>

Getting Started

  1. Install yall.js via npm:
npm install yall-js
  1. Include yall.js in your HTML:
<script src="node_modules/yall-js/dist/yall.min.js"></script>
  1. Add the lazy class and data-src attribute to your images or videos:
<img class="lazy" data-src="image.jpg" src="placeholder.jpg" alt="Lazy loaded image">
  1. Initialize yall.js in your JavaScript:
document.addEventListener("DOMContentLoaded", yall);

Competitor Comparisons

17,454

High performance and SEO friendly lazy loader for images (responsive and normal), iframes and more, that detects any visibility changes triggered through user interaction, CSS or JavaScript without configuration.

Pros of lazysizes

  • More comprehensive feature set, including plugins for advanced functionality
  • Supports a wider range of browsers, including older versions
  • Automatic size calculation for responsive images

Cons of lazysizes

  • Larger file size due to more features (11KB vs 1KB for yall.js)
  • More complex setup and configuration for advanced features
  • Potentially higher performance overhead for simpler use cases

Code Comparison

lazysizes:

<img data-src="image.jpg" class="lazyload" />
<script src="lazysizes.min.js" async=""></script>

yall.js:

<img data-src="image.jpg" class="lazy" />
<script src="yall.min.js"></script>
<script>
  document.addEventListener("DOMContentLoaded", yall);
</script>

Both libraries use similar markup for lazy-loaded images, but lazysizes automatically initializes itself, while yall.js requires manual initialization. lazysizes offers more options and features out of the box, whereas yall.js focuses on simplicity and performance for basic lazy loading scenarios.

The choice between these libraries depends on the project's requirements. lazysizes is better suited for complex projects with diverse lazy loading needs, while yall.js is ideal for simpler implementations prioritizing small file size and minimal setup.

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

Pros of lozad.js

  • Smaller file size (1.9KB gzipped) compared to yall.js (2.6KB gzipped)
  • Supports more than just images, including iframes and background images
  • Uses Intersection Observer API for better performance

Cons of lozad.js

  • Less browser support due to reliance on Intersection Observer API
  • Fewer customization options for loading behavior
  • Limited built-in support for responsive images

Code Comparison

lozad.js:

const observer = lozad();
observer.observe();

yall.js:

document.addEventListener("DOMContentLoaded", yall);

Both libraries aim to provide lazy loading functionality, but lozad.js offers a more modern approach with broader element support at the cost of compatibility. yall.js provides better browser support and more customization options but has a slightly larger file size. The code comparison shows that lozad.js requires explicit initialization of the observer, while yall.js can be set up with a simple event listener.

LazyLoad is a lightweight, flexible script that speeds up your website by deferring the loading of your below-the-fold images, backgrounds, videos, iframes and scripts to when they will enter the viewport. Written in plain "vanilla" JavaScript, it leverages IntersectionObserver, supports responsive images and enables native lazy loading.

Pros of vanilla-lazyload

  • More comprehensive documentation and examples
  • Supports a wider range of use cases, including background images and video elements
  • Offers more customization options and callbacks

Cons of vanilla-lazyload

  • Slightly larger file size compared to yall.js
  • May have a steeper learning curve due to more features and options

Code Comparison

vanilla-lazyload:

const lazyLoadInstance = new LazyLoad({
  elements_selector: ".lazy",
  threshold: 300,
  callback_enter: (element) => {
    console.log("Entered viewport:", element);
  }
});

yall.js:

document.addEventListener("DOMContentLoaded", () => {
  yall({
    observeChanges: true,
    threshold: 300,
    events: {
      load: (event) => {
        console.log("Loaded:", event.target);
      }
    }
  });
});

Both libraries offer similar core functionality for lazy loading images and other media. vanilla-lazyload provides more built-in features and customization options, while yall.js focuses on simplicity and a smaller footprint. The choice between the two depends on the specific project requirements, such as the need for advanced features or a lightweight solution.

Vanilla JavaScript plugin for lazyloading images

Pros of lazyload

  • Supports more types of media, including iframes and background images
  • Offers more customization options and callbacks
  • Has a longer development history and larger user base

Cons of lazyload

  • Larger file size (11.1 KB minified vs 1.5 KB for yall.js)
  • More complex setup and configuration
  • May have slightly higher performance overhead due to additional features

Code Comparison

lazyload:

const lazyLoadInstance = new LazyLoad({
    elements_selector: ".lazy",
    load_delay: 300,
    threshold: 0
});

yall.js:

document.addEventListener("DOMContentLoaded", () => {
    yall({
        observeChanges: true,
        threshold: 300
    });
});

Both libraries aim to provide lazy loading functionality for images and other media, but they differ in their approach and feature set. lazyload offers more extensive options and supports a wider range of use cases, while yall.js focuses on simplicity and performance with a smaller footprint.

The choice between the two depends on the specific requirements of your project, such as the types of media you need to lazy load, the level of customization needed, and performance considerations.

Lazy load your component, image or anything matters the performance.

Pros of react-lazyload

  • Specifically designed for React applications, offering seamless integration
  • Provides more granular control over lazy loading behavior
  • Supports both vertical and horizontal lazy loading

Cons of react-lazyload

  • Limited to React applications, unlike yall.js which is framework-agnostic
  • May require more setup and configuration compared to yall.js
  • Less actively maintained, with fewer recent updates

Code Comparison

react-lazyload:

import LazyLoad from 'react-lazyload';

<LazyLoad height={200} once>
  <img src="image.png" />
</LazyLoad>

yall.js:

<img data-src="image.png" class="lazy" src="placeholder.jpg" alt="Image">

<script>
  document.addEventListener("DOMContentLoaded", yall);
</script>

Key Differences

  • react-lazyload is a React-specific solution, while yall.js is a vanilla JavaScript library
  • yall.js uses a data-src attribute for lazy loading, whereas react-lazyload wraps components
  • react-lazyload offers more customization options within React components
  • yall.js has a simpler setup process for non-React projects

Use Cases

  • Choose react-lazyload for React-based projects requiring fine-tuned lazy loading
  • Opt for yall.js in multi-framework environments or simpler implementations

Both libraries effectively implement lazy loading, but their ideal use cases differ based on project requirements and technology stack.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

yall.js (Yet Another Lazy Loader)

Uncompressed size. gzip size. Brotli size.

yall.js is a SEO-friendly lazy loader for <video> elements as well as CSS background images. It works in all modern browsers. It uses Intersection Observer where available. yall.js can also monitor the DOM for changes using Mutation Observer to lazy load elements that have been appended to the DOM after initial load, which may be desirable for single page applications.

yall.js 4 removes lazy loading for <img>, <picture>, and <iframe> elements, as native lazy loading covers these use cases. However, yall.js 4 retains the ability to lazy load autoplaying <video> (ala animated GIFs), lazy loading <video> element poster images, as well as CSS background images.

To use yall, grab yall.min.js (or yall.min.mjs if you're the modern sort) from the dist directory and slap it on your page. You can also install it with npm:

npm install yall-js

Usage

This is version 4 of yall.js, and introduces a named export named yall rather than a single default export:

// Import y'all
import { yall } from "yall-js";

// Invoke!
yall();

The above syntax is sufficient if you don't want to pass in any options. If you do want to specify options, you'll need to use a slightly more verbose syntax:

// Import y'all
import { yall } from "yall-js";

// Invoke!
yall({
  observeChanges: true
});

From there, lazy loading elements depends on what you want to lazy load. Let's take a look at what you can do with it.

<video>

yall.js covers two possible lazy loading patterns for video.

Lazy-loading videos intended as replacements for animated GIFs

yall.js can lazy load <video> elements intended to replace animated GIFs with autoplaying videos:

<video class="lazy" autoplay loop muted playsinline>
  <source data-src="video.webm" type="video/webm">
  <source data-src="video.mp4" type="video/mp4">
</video>

The pattern is largely the same as it is with <picture>, only the lazy class is applied to the <video> element. Tip: If you're embedding videos that don't emulate animated GIFs (i.e., non autoplaying video), it's better to not lazy load them. Instead, use the preload attribute to defer loading of video content. Please also note that video autoplay policies can change at any time, meaning your video may not autoplay on some platforms! Such behaviors are not bugs, but rather features designed to respect users' bandwidth and preferences. Filing issues related to video autoplay issues will likely be rejected, as yall.js can't (and won't) override browser policies.

Lazy-loading poster placeholder images for non-autoplaying video

Sometimes you have video you'd rather not autoplay, such as those with an audio track. Or, perhaps you want to be more considerate of your user's bandwidth (how nice of you). In these cases, the poster attribute can be used to load a placeholder image. However, these images can also be rather large, especially if you have a number of videos on the page that use this pattern. You can lazy load poster images with the following markup pattern:

<video class="lazy" data-poster="placeholder.jpg" controls preload="none">
  <source src="video.webm" type="video/webm">
  <source src="video.mp4" type="video/mp4">
</video>

This pattern is slightly different than the one before it. Because we're not trying to emulate animated GIFs, we've removed a number of attributes from the <video> element that aren't necessary in this case:

  1. We've done away with the usual data-src attribute, and specified preload="none" to ensure the browser doesn't preload any portion of the video (which, depending on the browser, can't be guaranteed).
  2. To lazy load the poster image itself, we specify the image to load in a data-poster attribute.
  3. The controls attribute is added here to allow the user to control video playback.

Note: For the sake of your users, don't mix the above markup patterns. If a video is going to use autoplay to replace an animated image, lazy loading a placeholder image via data-poster isn't necessary. Furthermore, if you're unsure of what to do, let browsers handle this stuff and don't use yall.js to manage loading of videos at all!

CSS images

Last, but not least, you can use yall.js to lazy load images referenced in CSS. This might be useful if you have a very large background-image you'd like to defer. Proper use of this feature requires both HTML and CSS. To start, let's say you have a <div> that loads a very large masthead background-image:

<!-- I bet this loads a giant stock photo! -->
<div class="masthead lazy-bg"></div>

The key here is the lazy-bg class, which is a class yall.js looks for (and can be changed in the options). When yall.js sees elements with this class, it will remove that class and replace it with a class of lazy-bg-loaded (also changeable in the options). From here, it's up to you to author CSS that makes use of this class to swap the image in. Such CSS might look like this:

/* Pre-lazy loading styles */
.masthead {
  background: #e6e6e6; /* A little placeholder color */
  height: 16.66vw;
  margin: 0 0 1rem;
}

/* BAM! Lazy loaded! */
.masthead.lazy-bg-loaded {
  background: url("masthead.jpg");
}

This works because, unlike HTML which loads most resources regardless of their visibility, CSS loads resources only if the current layout builds a CSSOM which includes them. That means if your document's style tree changes later on to request a background image, the browser will fetch it the moment the change is applied. Leaning on this behavior is more sensible than using a mess of data- attributes pointing to possible image candidates, which could potentially add a bunch of extra markup and introduce edge cases that are difficult to code for.

What about users without JavaScript?

Slap on some <noscript>:

<!-- A `<video>` example: -->
<video class="lazy" preload="none" autoplay loop muted playsinline>
  <source data-src="video.webm" type="video/webm">
  <source data-src="video.mp4" type="video/mp4">
</video>
<noscript>
  <video preload="none" autoplay loop muted playsinline>
    <source src="video.webm" type="video/webm">
    <source src="video.mp4" type="video/mp4">
  </video>
</noscript>

<!-- A `<video>` example: -->
<video class="lazy" preload="none" autoplay loop muted playsinline data-poster="img/video-poster.jpg">
  <source src="video.webm" type="video/webm">
  <source src="video.mp4" type="video/mp4">
</video>
<noscript>
  <video preload="none" autoplay loop muted playsinline poster="img/video-poster.jpg">
    <source src="video.webm" type="video/webm">
    <source src="video.mp4" type="video/mp4">
  </video>
</noscript>

Then place a no-js class on the <html> element:

<html class="no-js">

Finally, add this one line <script> before any <link> or <style> elements in the document <head>:

<!-- Remove the no-js class on the <html> element if JavaScript is on -->
<script>document.documentElement.classList.remove("no-js")</script>

Normally, this script will remove the no-js class from the <html> element as the page loads, but if JavaScript is turned off, this never happens. From there, you can add some CSS that hides elements with a class of lazy when the no-js class is present on the <html> element:

/* Hide .lazy elements if JavaScript is off */
.no-js .lazy {
  display: none;
}

To see all these examples in action, clone the repo, install packages, run npm test, and check out the demos on your local machine at http://localhost:8080.

API options

When you call the main yall initializing function, you can pass an in an options object. Here are the current options available:

lazyClass

default: "lazy"
The element class used by yall.js to find elements to lazy load. Change this is if a class attribute value of lazy conflicts with your application.

lazyBackgroundClass

default: "lazy-bg"
The element class used by yall.js to find elements to lazy load CSS background images for. Change this if you'd prefer not to use the default.

lazyBackgroundLoaded

default: "lazy-bg-loaded"
When yall.js finds elements using the class specified by lazyBackgroundClass, it will remove that class and put this one in its place. This will be the class you use in your CSS to bring in your background image when the affected element is scrolled into the viewport.

threshold

default: 200
The threshold (in pixels) for how far elements need to be within the viewport to begin lazy loading.

events

default: {}
An object of events that get sent directly to addEventListener for each element to be lazy loaded. Rather than building an opinionated, bespoke event management system, this system gets out of your way and lets you to specify whatever events are possible to bind with addEventListener. Here's an example below:

yall({
  events: {
    // The object key is sent as the first argument to `addEventListener`,
    // which is the event. The corresponding value can be the callback if you
    // don't want to send any options to `addEventListener`.
    load: function (event) {
      if (!event.target.classList.contains("lazy")) {
        event.target.classList.add("yall-loaded");
      }
    },
    // If we want to pass options to the third argument in `addEventListener`,
    // we can use a nested object syntax like so:
    error: {
      // Here, the `listener` member is the callback.
      listener: function (event) {
        if (!event.target.classList.contains("lazy") && event.target.nodeName == "VIDEO") {
          event.target.classList.add("yall-error");
        }
      },
      // The option below is sent as the third argument to `addEventListener`,
      // offering more control over how events are bound. If you want to
      // specify `useCapture` in lieu of options pass a boolean here instead.
      options: {
        once: true
      }
    }
  }
});

Events for yall.js are bound at initialization time (often DOMContentLoaded). This means that some events could fire multiple times, depending on the event. For instance, in the above load event example, you can see that we check for the default class of lazy on the element. This is because the load event could fire when the initial image placeholder loaded (if one is specified) and when the final image is lazy loaded.

The advantage of this approach is that you can do pretty much anything you want in any of the events on the elements yall.js observes. The disadvantage is that it places the responsibility squarely on you to manage events. If you think yall.js has a bug in this behavior, do your due diligence to research whether your event callback code is buggy before filing issues.

observeChanges

default: false
Use a MutationObserver to monitor the DOM for changes. This is useful if you're using yall.js in a single page application and want to lazy load resources for markup injected into the page after initial page render.

observeRootSelector

default: "body"
If observeChanges is set to true, the value of this string is fed into document.querySelector to limit the scope in which the Mutation Observer looks for DOM changes. The <body> element is monitored by default, but you can confine the observer to any valid CSS selector (e.g., #main-wrapper).

mutationObserverOptions

default: { childList: true, subtree: true }
Options to pass to the MutationObserver instance. Read this MDN guide for a list of options. It's very possible that changing this value could result in yall.js failing to lazy load resources that are appended to the DOM later on.

Words of advice

Unlike previous versions of yall-js, compatibility back to IE 11 is no longer a goal. If you need compatibility with older browsers, install the previous release of yall.js like so:

npm i yall@3.2.0

Also, it is not this script's job to minimize layout shifts for you. Use appropriate width and height attributes, styles, and lightweight placeholders for your images.

For <video> elements, avoid lazy loading a placeholder with the data-poster attribute for autoplaying videos and just use poster. On the other hand, do consider lazy loading a placeholder image with data-poster for non-autoplaying videos. Or you can opt not to use a poster image. Your website, your call.

Also, do not lazy load resources that are likely to near the top of the page—or "above the fold", as it were. Doing so is an anti-pattern in that those resources will not begin loading until yall.js has been loaded, which may take much longer than if those resources were loaded normally. Such a pattern will negatively affect your page's LCP.

Contributing

Please read the contribution guidelines. If you think I'm some kind of grumpy crank after reading that, please remember that this is a hobby project you can use for free.

NPM DownloadsLast 30 Days