Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

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

License

NotificationsYou must be signed in to change notification settings

mfranzke/loading-attribute-polyfill

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

661 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

MIT licensenpm bundle sizeTotal downloads ~ NpmjsjsDelivr CDN downloadsCodacy BadgeKnown VulnerabilitiesCodeQLGitHub Super-Linterloading-attribute-polyfill on Npmjscode style: prettierXO code styleConventional CommitsJoin the chat at https://gitter.im/loading-attribute-polyfill/communityPRs WelcomeOpen Source LoveContributor 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 withsrcset and withinpicture, as well asiframe 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 standardloading="lazy" attribute onimg andiframe 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 providinganother 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 theother solution) or not (stay with this one) on your requirements and technical context.

  • Service Workers only run overHTTPS, for security reasons
  • Service Worker need to getregistered on first page visit
  • Only works onsame 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:

<linkrel="stylesheet"href="dist/loading-attribute-polyfill.css"/><scriptsrc="dist/loading-attribute-polyfill.umd.js"async></script>

or e.g. within JS

importloadingAttributePolyfillfrom"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 attributeclass="loading-lazy".)

Please keep in mind that it's important to even also includewidth andheight 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 articleshttps://css-tricks.com/do-this-to-improve-image-loading-on-your-website/ (with video) orhttps://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 tothe article "Browser-level image lazy-loading for the web" published on web.dev:

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

Simple image

<noscriptclass="loading-lazy"><imgsrc="simpleimage.jpg"loading="lazy"alt=".."width="250"height="150"/></noscript>

Image wrapped in a picture tag

<noscriptclass="loading-lazy"><picture><sourcemedia="(min-width: 40em)"srcset="simpleimage.huge.jpg 1x, simpleimage.huge.2x.jpg 2x"/><sourcesrcset="simpleimage.jpg 1x, simpleimage.2x.jpg 2x"/><imgsrc="simpleimage.jpg"loading="lazy"alt=".."width="250"height="150"/></picture></noscript>

Image withsrcset

<noscriptclass="loading-lazy"><imgsrc="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

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

Optional additional dependencies

In case you'd like to supportolder 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 theMicrosoft 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 closingbody HTML tag, as including it e.g. within thehead 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 amatchMedia 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 includedHTMLElement 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 atdemo/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 Firefoxlatest, macOS 10.14 (manually, localhost)
  • iOS

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

    • Google Chromelatest, Windows 10 (via CrossBrowserTesting)
    • Mozilla Firefoxlatest, 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 byCrossBrowserTesting

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 theloading="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]

About

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

Topics

Resources

License

Code of conduct

Stars

Watchers

Forks

Packages

No packages published

Contributors14


[8]ページ先頭

©2009-2026 Movatter.jp