Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

loading-attribute-polyfill

mfranzke13.7kMIT2.1.1

Fast and lightweight dependency-free vanilla JavaScript polyfill for native lazy loading / the awesome loading='lazy'-attribute.

lazy loading, native lazy loading, img, image, iframe, polyfill, web development, javascript, html, front-end

readme

loading="lazy" attribute polyfill

Financial Contributors on Open Collective MIT license npm bundle size Total downloads ~ Npmjs jsDelivr CDN downloads Codacy Badge Known Vulnerabilities CodeQL GitHub Super-Linter loading-attribute-polyfill on Npmjs code style: prettier XO code style Conventional Commits Join the chat at https://gitter.im/loading-attribute-polyfill/community PRs Welcome Open Source Love Contributor Covenant

Fast and lightweight vanilla JavaScript polyfill for native lazy loading, meaning the behaviour to load elements right before they enter the viewport. Provides graceful degradation, and is - not just thatfor - SEO friendly. Handles images with srcset and within picture, as well as iframe elements. loading="lazy" will be a huge improvement for todays web performance challenges, so use and polyfill it today!

  • Released under the MIT license
  • Made in Germany. And supported by so many great people from all over this planet - see "Credits" accordingly.
  • Compatible down to Microsoft Internet Explorer 9

Features

  • Lightweight (see the badge above)
  • Web standards: supports the standard loading="lazy" attribute on img and iframe elements
  • Performance: it's based on highly efficient, best practice code.
  • SEO & crawlers: the image and iframe contents aren't being hidden from crawlers that aren't capable of scrolling.
  • Supporting HTML generating JavaScript frameworks through a method provided to reinit its functionality (see "Another solution, especially in combination with JavaScript framework usage" as well)

Core concepts

The polyfill was designed with the following concepts kept in mind:

  • dependency-free
  • using JavaScript with graceful degradation

Another solution, especially in combination with JavaScript framework usage

We're even also providing another solution, which main architectural decision is that we're using Service Worker to intercept the image and iframe contents network requests there. This comes with some aspects that are important to mention, that might be either acceptable (have a look at the other solution) or not (stay with this one) on your requirements and technical context.

  • Service Workers only run over HTTPS, for security reasons
  • Service Worker need to get registered on first page visit
  • Only works on same domain network requests

Whereas the first topic might not be a problem (anymore) on most websites – as this should be the de-facto standard nowadays – the second and third might be acceptable in your context, as this polyfill behaves as a progressive enhancement to provide the expected functionality even for non-supporting browsers both only on seconds pages request and any revisits and for same origin image and contents (iframe) requests even only.

Installation

First you'll need to integrate the JavaScript file into your code.

You may optionally load via NPM or Bower:

$ npm install loading-attribute-polyfill
$ bower install loading-attribute-polyfill

You could load the polyfill asynchronously as well: https://output.jsbin.com/codelib/1

Integration

Include one of the provided JavaScript files depending on your setup plus the CSS file:

<link rel="stylesheet" href="dist/loading-attribute-polyfill.css" />
<script src="dist/loading-attribute-polyfill.umd.js" async></script>

or e.g. within JS

import loadingAttributePolyfill from "node_modules/loading-attribute-polyfill/dist/loading-attribute-polyfill.module.js";

Afterwards, you need to wrap all of your <img> and <iframe> HTML tags (in the case of <picture> use the complementary <source> HTML tags) that you'd like to lazy load with a <noscript> HTML tag (with the attribute class="loading-lazy".)

Please keep in mind that it's important to even also include width and height attributes on <img> HTML tags, as the browser could determine the aspect ratio via those two attributes values being set (even if you overwrite them via CSS), compare to the great work by Jen Simmons on this topic, e.g. within these articles https://css-tricks.com/do-this-to-improve-image-loading-on-your-website/ (with video) or https://css-tricks.com/what-if-we-got-aspect-ratio-sized-images-by-doing-almost-nothing/

And please "Avoid lazy-loading images that are in the first visible viewport", compare to the article "Browser-level image lazy-loading for the web" published on web.dev:

You should avoid setting loading=lazy for any images that are in the first visible viewport. It is recommended to only add loading=lazy to images which are positioned below the fold, if possible.

Simple image

<noscript class="loading-lazy">
    <img src="simpleimage.jpg" loading="lazy" alt=".." width="250" height="150" />
</noscript>

Image wrapped in a picture tag

<noscript class="loading-lazy">
    <picture>
        <source
            media="(min-width: 40em)"
            srcset="simpleimage.huge.jpg 1x, simpleimage.huge.2x.jpg 2x"
        />
        <source srcset="simpleimage.jpg 1x, simpleimage.2x.jpg 2x" />
        <img
            src="simpleimage.jpg"
            loading="lazy"
            alt=".."
            width="250"
            height="150"
        />
    </picture>
</noscript>

Image with srcset

<noscript class="loading-lazy">
    <img
        src="simpleimage.jpg"
        srcset="
            simpleimage.1024.jpg 1024w,
            simpleimage.640.jpg   640w,
            simpleimage.320.jpg   320w
        "
        sizes="(min-width: 36em) 33.3vw, 100vw"
        alt="A rad wolf"
        loading="lazy"
    />
</noscript>

Iframe

<noscript class="loading-lazy">
    <iframe
        src="https://player.vimeo.com/video/87110435"
        width="320"
        height="180"
        loading="lazy"
    ></iframe>
</noscript>

Optional additional dependencies

In case you'd like to support older versions of Microsoft Edge, Microsoft Internet Explorer 11 or Apple Safari up to 12.0, you could (conditionally) load an IntersectionObserver polyfill:

https://www.npmjs.com/package/intersection-observer

Nevertheless this polyfill would still work in those browsers without that other polyfill included, but this small amount of users wouldn't totally benefit from the lazy loading functionality - we've at least got you partly covered by using the Microsoft proprietary lazy loading resource hints.

Internet Explorer 9 & Internet Explorer 10

Internet Explorer 9 and 10 have bugs where the 'interactive' state can be fired too early before the document has finished parsing.

Source: https://developer.mozilla.org/en-US/docs/Web/API/Document/readyState

That for you would need to include the polyfill the latest within the HTML code, like the nearest to the closing body HTML tag, as including it e.g. within the head section might lead to an unexpected state, so that in worst case the images might not get loaded.

Internet Explorer 9

The polyfill has been enhanced to even also provide it's functionality on IE9. But please keep in mind to even also include a matchMedia polyfill.

And the images are still displaying an error in the demo on IE9, as most likely (from my understanding) this browser doesn't work with the HTTPS protocol by GitHub pages any more, but the src-attributes values are correctly rewritten after all.

API

In case that you're dynamically adding HTML elements within the browser, you could call the following method with an included HTMLElement object, like e.g.:

loadingAttributePolyfill.prepareElement(document.querySelector('main noscript.loading-lazy'));

Demo

See the polyfill in action either by downloading / forking this repository and have a look at demo/index.html, or at the hosted demo: https://mfranzke.github.io/loading-attribute-polyfill/demo/

Further implementations - Kudos for that

WordPress

Nico23 has developed a WordPress plugin: https://wordpress.org/plugins/native-lazyload-polyfill/ (which is much better than the one by Google !)

PHP Twig Extension

@tim-thaler has developed a PHP Twig Extension: https://github.com/tim-thaler/twig-loading-lazy

Craft Twig Loading Lazy plugin

@tim-thaler has even also developed a Craft Twig Loading Lazy plugin: https://github.com/tim-thaler/craft-twig-loading-lazy

Credits

Credits for the initial kickstarter / script to @Sora2455 for better expressing my ideas & concepts and support by @cbirdsong, @eklingen, @DaPo, @nextgenthemes, @diogoterremoto, @dracos, @Flimm, @TomS-, @vinyfc93, @JordanDysart and @denyshutsal. Thank you very much for that, highly appreciated !

Tested with

  • Mac

    • Safari 14, macOS 11 (via CrossBrowserTesting)
    • Mozilla Firefox latest, macOS 10.14 (manually, localhost) <!-- - macOS 10.14, Safari 12 (via CrossBrowserTesting)
    • macOS 10.13, Safari 11 (via CrossBrowserTesting) -->
  • iOS

    • Mobile Safari 12.0, iPad 6th Generation Simulator (manually)
  • Windows

    • Google Chrome latest, Windows 10 (via CrossBrowserTesting)
    • Mozilla Firefox latest, Windows 10 (via CrossBrowserTesting)
    • Microsoft Edge version 18, Windows 10 (manually, localhost)
    • Microsoft Internet Explorer version 11, Windows 10 (via CrossBrowserTesting)
    • Internet Explorer 9.0.8112.16421, Windows 7 SP1 (manually, localhost)

Big Thanks

Cross-browser testing platform provided by CrossBrowserTesting

CrossBrowserTesting

Things to keep in mind

  • The HTML demo code is meant to be simple
  • This polyfill doesn't (so far) provide any functionality for the loading="eager" value, as this was released even already, but still seems to be in the measure, learn and improvements phase.

More information on the standard

Outro

If you're trying out and using my work, feel free to contact me and give me any feedback. I'm curious about how it's gonna be used.

And if you do like this polyfill, please consider even also having a look at the other polyfill we've developed: https://github.com/mfranzke/datalist-polyfill/

Contributors

Code Contributors

This project exists thanks to all the people who contribute. [Contribute].

Financial Contributors

Become a financial contributor and help us sustain our community. [Contribute]

Individuals

Organizations

Support this project with your organization. Your logo will show up here with a link to your website. [Contribute]

changelog

Changelog

All notable changes to this project will be documented in this file.

The format is based on Keep a Changelog and this project adheres to Semantic Versioning. And the commit messages from Conventional Commits are being used.

[Unreleased]

Added

  • Method for reinit with a specific scope without the <noscript> HTML tag, compare to #94
  • CONTRIBUTING.MD
  • Description on how to use with MutationObserver (won't be included within the polyfill itself)
  • Test case for dynamic images

[2.1.0] - 2022-05-15

Added

  • browser field to package.json instead of main entry again

Changed

  • Updated devDependencies

[2.0.2] - 2022-04-10

It's polyfills birthday (okay, it has been yesterday), so I did a lot of housekeeping and even also released a new version of the polyfill with another concept (using Service Worker to prevent loading images and iframes contents). Check it out and evaluate its usage in your project: https://github.com/mfranzke/loading-attribute-polyfill-with-serviceworker

Added

Changed

  • build: updated gitignore file according to githubs default content
  • documentation: a lot of simple optimizations, like e.g. added further notice on the users browser capabilities
  • updated a lot of devDependencies
  • master to main as the default branch
  • using Ndoe 16 now (for development and CI/CD)
  • replaced dependencies update status badge

Fixed

  • documentation: crossbrowsertestings logo URL
  • documentation: codacy badge URL
  • test: webdriverio tests

[2.0.1] - 2021-05-13

Added

  • build: added CI/CD yaml for pull-requests 2f59306

Changed

  • refactor: removed two CSS files which aren't generated any more by microbundle c960f13
  • test: specified the browser versions within their test-browser-names cacceaf
  • Formatted the code with xo and prettier again
  • build: replaced manual versioning via np package 0b4f9ef
  • build(deps-dev): bump xo from 0.39.1 to 0.40.1 (#170) b4b58eb
  • build(deps-dev): bump prettier from 2.2.1 to 2.3.0 (#168) 75696fc
  • build(deps-dev): bump @commitlint dependencies ce81f5d
  • build(deps-dev): bump webdriverio dependencies
  • build(deps-dev): bump html-validate from to 4.11.0
  • build(deps-dev): bump xo from 0.38.2 to 0.39.1 (#143) 2514fcb

Fixed

  • Description within the README on the correct UMD JavaScript files to include

[2.0.0] - 2021-04-09

It's polyfills birthday today! Yeah! So to cheer this, we're releasing the new major release.

Added

  • Further entries for npm package to ignore files
  • Adapted code of conduct

Changed

  • Moved the webdriverio config file to its subdirectory
  • Corrected the bower ignore entries
  • Bump html-validate from 4.8.0 to 4.9.0 (#126)
  • Code regarding codacys feedback
  • Bump webdriverio dependencies

[2.0.0-rc.1] - 2021-04-03

Added

  • Automated Mozilla Firefox testing via crossbrowsertesting
  • Automated Microsoft Internet Explorer 9 testing via crossbrowsertesting

Changed

  • build(deps-dev): bump husky from 5.1.3 to 6.0.0 (a.o. !110)
  • build(deps-dev): bump html-validate from 4.6.1 to 4.8.0
  • build(deps-dev): bump webdriverio dependencies
  • Optimized the demo pages functionality for dynamic images, by adding a button
  • refactor: replacing requestAnimationFrame by will-change: contents (CSS)
  • build(deps-dev): bump @commitlint dependencies from 12.0.1 to 12.1.1
  • chore: moved source file to subfolder for better structure
  • some formatting and codacy feedback

[2.0.0-rc.0] - 2021-03-22

Added

  • GitHub's static analysis engine CodeQL to check against our repository's source code to find security vulnerabilities
  • Dependabot to ensure devDependencies are up to date (!106)

Changed

  • devDependency: bump husky from 5.1.2 to version 5.1.3
  • devDependency: bump html-validate from 4.6.0 to 4.7.1 (commit 801b314, !105 and !109)

Fixed

  • testing: updated the tools and removed some old code to make crossbrowsertesting.com work again (!100)
  • browsers capabilities: we need to differentiate in between image and iframe capability, as Firefox only supports images for now, but not iframes

[2.0.0-beta.1] - 2021-03-04

Changed

  • BREAKING CHANGE: Even also generate JS modules from now on supported by microbundle, added the relevant property entries within the package.json directing to those files, that are now stored within the dist/ folder (see migration guide #19, #87, #39)

[2.0.0-beta.0] - 2021-03-04

Fixed

  • BREAKING CHANGE: wrapping the <picture> HTML tag instead of its content with <noscript> to prevent W3C HTML validator errors (see migration guide #90)

[1.5.4] - 2020-05-23

Changed

  • Updated webdriverio, husky, prettier and xo dependencies
  • Replaced Greenkeeper by Snyk for vulnerabilities scanning
  • Formatted code by prettier
  • husky: moved the hook to the dedicated config file
  • README: reordered the badges

Fixed

  • README: Position of Gitter badge
  • npmignore: added necessary folder

[1.5.3] - 2020-03-22

Changed

  • Updated webdriverio and prettier dependencies

Fixed

  • build: *.min.js files should't get prettified

[1.5.2] - 2020-03-19

Added

  • improvement(prettier): run prettier when committing files
  • a minzipped size badge

Changed

  • Formatting and code & content optimizations
  • xo: added further rules for IE9 compatibility

[1.5.1] - 2020-03-15

Fix

  • Corrected some metadata regarding the packages

[1.5.0] - 2020-03-15

Changed

  • Updated webdriverio, commitlint and xo dependencies
  • docs: further clarifications
  • IE9 & IE10: removed .dataset reliance

Fixed

  • IE9 & IE10: not deleting dataset items for IE9 compatibility #66
  • IE9 & IE10: added section within the docs on including the polyfill JS file at the end of the body

[1.4.1] - 2020-02-26

Changed

  • Updated webdriverio, husky and xo dependencies
  • Optimized the .npmignore file

[1.4.0] - 2020-01-25

Added

  • Commitlint & husky for CI

Changed

  • Update placeholder to SVG to prevent reflow on lazyloaded images #48
  • Updated webdriverio and xo dependencies

Fixed

  • README needed better wording to avoid confusion on installation/integration process #46

[1.3.1] - 2019-11-10

Fixed

  • Added another file to the .npmignore, nevermind ...

[1.3.0] - 2019-11-10

Added

  • Gitter badge
  • Graceful degradation and functionality for IE9 #41
  • Updated with some more supporters

Changed

  • Updated prettier and webdriverio dependencies
  • Further enhanced the documentation, like e.g. for #33

Fixed

  • Reduced the weight of the NPM package by adding a .npmignore file
  • Typos in the docs

[1.2.0] - 2019-10-15

Added

  • Crawler/"SEO" capabilities
  • Testing: Further browsers and activated the video-recording
  • Lots of further information and documentation
  • Codacy, dependency and Greenkeeper (#18) integrations and badges, yeah !
  • Comment within the demo page clarifying the images content #8
  • Links to further implementations / plugins & extensions

Changed

  • Made changes regarding to xo/prettier tools and codacys (#12) remarks
  • Some even smaller base64 image as an image replacement
  • Loading the sample images locally
  • Update xo to version 0.25
  • Updated webdriver.io's packages to version 5.13.2
  • Code simplifications

Fixed

  • Outdated JSBin link
  • Markdown regarding some readers/interpreters malfunctions

[1.1.0] - 2019-08-15

Changed

  • Added IE, EDGE < version 16 and Safari < version 12 support

[1.0.1] - 2019-08-10

Changed

  • Corrected both the demo-page as well as the documentation on the aspect of wrapping the <source> HTML tags as well

[1.0.0] - 2019-08-10

Added

  • Comment regarding asynchronous loading
  • Webdriver.io testing

Changed

  • BREAKING CHANGE: You'll need to also wrap the <source> HTML tags within the <picture> tags with <noscript>

Fix

  • Documents markup regarding codacy suggestions
  • Corrected sample image measurements
  • The images didn't load lazily in Safari, but directly, as reported with #3
  • Displaying the images on smaller viewports on the sample page

[0.2.0] - 2019-05-22

Added

  • Changelog
  • Codacy integration and badge
  • Code examples
  • Optional additional dependencies section within the README
  • Optional polyfill for the demo page
  • "Conventional Commits" support as well as their badge - yeah !

Changed

  • Docs formatting
  • Some docs content enhancements
  • Internal namings within the JS file

[0.1.2] - 2019-05-04

Added

  • Documentation

[0.1.1] - 2019-05-01

Added

  • CHANGELOG.md file

[0.1.0] - 2019-05-01

Added

  • Initial files
  • npm and bower support
  • code formatting and linting