Skip to content

Latest commit

 

History

History
269 lines (198 loc) · 13.9 KB

File metadata and controls

269 lines (198 loc) · 13.9 KB

loading="lazy" attribute polyfill with Service Worker

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

Fast and lightweight dependency-free vanilla JavaScript polyfill for native lazy loading / the awesome loading='lazy'-attribute, depending on Service Worker (kudos for that great idea to @garygreen !!!)

  • 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 17

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.
  • JavaScript framework friendly*

*As some JavaScript frameworks would like to "own the DOM", it's not a good practice to try to manipulate the HTML content by our polyfill. That for this solution hooks into the network connection (by a Service Worker that you would need to register) to intercept the image and iframe contents network requests. This gives us much more flexibility on the usage contexts, but has some drawbacks, see section "Prerequisites".

Core concepts

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

  • dependency-free
  • using JavaScript with graceful degradation

Prerequisites

The main architectural decision to differentiate from other solutions like loading-attribute-polyfill is that we're using Service Worker to intercept the image and iframe contents network requests. This comes with some aspects that are important to mention, that you might want to evaluate 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 sites – 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-with-serviceworker
$ bower install loading-attribute-polyfill-with-serviceworker

Integration

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

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

or e.g. within JS

import loadingAttributePolyfillWithServiceWorker from "node_modules/loading-attribute-polyfill-with-serviceworker/dist/loading-attribute-polyfill-with-serviceworker.module.js";

Additional information on your image and document (iframe) references

Afterwards, you need to add a query to all of your <img> (?loading=lazy&image-width=250&image-height=150) and <iframe> (?loading=lazy) HTML tags (in the case of <picture> use the complementary <source> HTML tags) that you'd like to lazy load. The included image-width and image-height values should match the width- and height-attribute values of each asset.

Generally set dimensions on your images

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.

Register a Service Worker

Furthermore you would either need to integrate the code out of loading-attribute-polyfill-with-serviceworker.sw.js to your existing Service Worker or register one by yourself – please keep in mind that it's very important to add the feature detection to the Service Workers URL within the navigator.serviceWorker.register methods parameter, as we're transfering that information on the users enviroments capabilities via this way.

if ("serviceWorker" in navigator) {
	// Differentiate in between the Service Worker scripts for the different browser capabilities / support
	navigator.serviceWorker.register(
		"loading-attribute-polyfill-with-serviceworker.sw.js?loading-images=" +
			("loading" in HTMLImageElement.prototype) +
			"&loading-iframes=" +
			("loading" in HTMLIFrameElement.prototype)
	);
}

Example code

Simple image

<img
	src="simpleimage.jpg?loading=lazy&image-width=250&image-height=150"
	loading="lazy"
	alt=""
	width="250"
	height="150"
/>

Image wrapped in a picture tag

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

Image with srcset

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

Iframe

<iframe
	src="iframe.html?loading=lazy"
	width="320"
	height="180"
	loading="lazy"
></iframe>

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.:

loadingAttributePolyfillWithServiceWorker.prepareElement(
	document.querySelector('main [loading="lazy"]')
);

In general we recommend to use the Web Standard of customized built-in elements extends to achieve this, by adding an is-attribute to the related element and registering those with JavaScript afterwards:

<img
	src="simpleimage.jpg?loading=lazy&image-width=250&image-height=150"
	loading="lazy"
	alt=""
	width="250"
	height="150"
	is="loading-image"
/>
import loadingAttributePolyfillWithServiceWorker from "loading-attribute-polyfill-with-serviceworker";

// See https://html.spec.whatwg.org/multipage/indices.html#element-interfaces
// for the list of other DOM interfaces.
class LoadingImages extends HTMLImageElement {
	constructor() {
		super(); // Always call super() first in the constructor.
		// Call for preparing the sample image element included the latest dynamically inserted
		loadingAttributePolyfillWithServiceWorker.prepareElement(this);
	}
}

customElements.define("loading-image", LoadingImages, { extends: "img" });

compare to the code within demo/loading-attribute-polyfill-with-serviceworker.custom-builtin-extend.image.js (or demo/loading-attribute-polyfill-with-serviceworker.custom-builtin-extend.iframe.js for iframe elements).

In case that you even also would like to support Safari / WebKit browsers, you'll need a polyfill as this engine doesn't support that part of the Custom Elements standard so far: https://www.npmjs.com/package/@ungap/custom-elements

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-with-serviceworker/demo/

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. And especially to @garygreen for coming up with the great idea to use Service Worker. 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)
  • 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/