Giter VIP home page Giter VIP logo

auto-lazyload's Introduction

Auto Lazy Load

Why?

While lazy loading is hailed as a game-changer in optimizing web performance, not all implementations are created equal. Traditional lazy loaders may inadvertently delay crucial content, leading to detrimental effects on your site's Largest Contentful Paint (LCP). Read more about this and about the Largest Contentful Paint (LCP).

How?

This library allows you to lazyload images, videos, and background images using the Intersection Observer API and the MutationObserver API in order to check when an element is in view. What differs with the common lazy loading implementation is that it doesn't require markup, it's very lightweight and fast to load, remaining full-featured and easy to use.

Usage

Add the script just after the body tag.

Using the iife version

<html>
    <head>...</head>
    <body>
        <script src="https://unpkg.com/auto-lazyload"></script>
        ... the rest of your code ...
    </body>
</html>
...

Using the esm version

install the library with npm install auto-lazyload or yarn add auto-lazyload.

Then import the library with:

<html>
    <head>...</head>
    <body>
    <script type="module">
        import AutoLazyLoad from 'auto-lazyload';
        AutoLazyLoad({
            on: 'lazy',
            loading: 'lazy-loading',
            failed: 'lazy-failed',
            loaded: 'lazy-loaded',
            attribute: 'data-lazy',
            nativeSupport: false,
            fetchprioritySupport: true
        });
    </script>
    ... the rest of your code ...
    </body>
</html>
...

User Configurable Options

If needed, you have the flexibility to customize the lazy loading behavior by setting the lazyloadOptions object in the window object before the document is loaded. This allows you to override the default options to tailor lazy loading according to your specific requirements.

Example:

window.autolazy = {
    on: 'my-lazy', // the class name for the active lazy loaded image
    loading: 'my-lazy-loading', // the class name for the lazy loading image
    failed: 'my-lazy-failed', // the class name for the failed image
    loaded: 'my-lazy-loaded', // the class name for the lazy loaded image
    attribute: 'data-lazy', // the dataset name for the lazy loaded image (used internally but configurable)
    nativeSupport: false, // whether to use the native lazyload (e.g. loading="lazy") or not
    fetchprioritySupport: true, // whether to add the fetchpriority attribute to the page head or not
    // The intersectionObserverOptions can also be set here
    // https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver#instance_properties
    selector: {
        root: null,
        rootMargin: "0px 0px 0px 0px",
        threshold: 0
    },
};

Api

  • Observer The intersection observer instance.
const observer = autolazy.observer;

// Example:
observer.rootMargin = "0px 0px 0px 0px";
observer.threshold = 0;

observer.observe(document.querySelector(".target"));
observer.unobserve(document.querySelector(".target"));
observer.disconnect();
  • Unmount Destroy the library and remove the event listeners.

autolazy.unmount()

  • Update a target Element Update the options for the specified target.

autolazy.update(".target")

  • Update Update the options for all targets.

autolazy.update()

  • Watch Add the specified target to the watch list.

autolazy.watch(document.querySelector(".target"))

  • Unveil Show the specified target.

autolazy.unveil(document.querySelector(".target"))

Additional Tricks

  • Skip auto lazy load

You can avoid the auto lazy load by adding the no-lazy class to the target element.

<img class="no-lazy" src="https://example.com/image.jpg" alt="this image is not lazyloaded" />
  • Disable the fetchpriority attribute

While the fetchPrioritySupport option is enabled by default, and it is recommended to keep it active, this can conflict with other plugins. If you need to disable it, this is possible by setting the fetchPrioritySupport option to false before the script is loaded.

window.autolazy = {fetchPrioritySupport: false};

Compatibility

  • The script is designed to work in modern browsers that support both Intersection Observer and Mutation Observer APIs.
  • If the IntersectionObserver API is not supported, the page will be loaded without lazy loading images but nothing else.

Contributing

See CONTRIBUTING.md

License

MIT

auto-lazyload's People

Contributors

erikyo avatar rcwd avatar

Stargazers

Huub avatar

Watchers

 avatar  avatar Huub avatar

Forkers

rcwd

auto-lazyload's Issues

Request to add setting for selective fetchpriority assignment

Hello,
In your locator.ts, your code adds fetchpriority to the images that are in the initial viewport. There are certain cases where it is preferable to selectively define the images to which you assign fetchpriority.

Could I suggest adding a setting to enable/disable this feature?

This is the code I am referring to:

if (isElement.nodeName === "IMG") {
	isElement.setAttribute("fetchpriority", "high");
	isElement.setAttribute("decoding", "async");

	const linkHeader = document.createElement("link");
	linkHeader.setAttribute("rel", "preload");
	linkHeader.setAttribute("as", "image");
	linkHeader.setAttribute(
		"href",
		(isElement as HTMLImageElement).src as string,
	);
	linkHeader.setAttribute("fetchpriority", "high");

	document.head.appendChild(linkHeader);
}

Thanks

Loading all background images despite css media query changes

Hello, i tried your js class and it is working well.
I have found an issue with background images added via js, i have this scenario:

<div id="mybgimage">.....</div>

<style>
#mybgimage{
    background-image: url(myimage.jpg);
}

@media only screen and (min-width: 592px){
    background-image: url(myimage-2.jpg);
}

@media only screen and (min-width: 1280px){
    background-image: url(myimage-3.jpg);
}

@media only screen and (min-width: 1536px){
    background-image: url(myimage-4.jpg);
}
<style>

What happens? By checking the Chrome console, all 4 bg images are downloaded in network tab.
Is there a way to fix this?

Thanks

Possibility to esclude items from lazy

Hello,
it should be a good idea to add a way to exclude some images to be lazyload.
For example by a default attribute nolazy, or maybe by adding a specific css class (.nolazy) or css path (.#mydiv .mywrapper .mypic).

Thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.