tvler / lazy-progressive-enhancement

A lazy image loader designed to enforce progressive enhancement and valid HTML.
http://tylerdeitz.co/lazy-progressive-enhancement/
MIT License
190 stars 10 forks source link
lazyload progressive-enhancement

Lazy Progressive Enhancement

Download, copy-paste, whatever ;)

View website

A lazy image loader designed to enforce progressive enhancement and valid HTML.

Not a framework, not a library, just a function (with clean af markup).

<noscript><img …></noscript>
loadMedia(
   element,
   onload,
   scroll
)

element: CSS String | NodeList | Element (optional) – loads all images if not set

onload: Function (optional)

scroll: Boolean (optional) – loads image when visible

Benefits of Lazy Progressive Enhancement

Other lazy loaders promote invalid HTML by omitting the src attribute, or aren't compatible for users without javascript.

Contents

Basic Usage

By default, the function targets every noscript element on the page.

Any attributes the image has in noscript (class / id / alt / etc) are kept.

HTML

<noscript><img alt="hello!" …></noscript>

JS

loadMedia()

End result HTML

<img alt="hello!" …>

Load Specific Images

You can specify what images to load by passing in either

  1. A CSS selector string (use if calling the function before DOMContentLoaded)
  2. A NodeList of noscripts (from something like document.querySelectorAll)
  3. A singular noscript Element (from something like document.querySelector)

HTML

<noscript id="this-one"><img …></noscript>
<noscript id="not-this-one"><img …></noscript>

JS

loadMedia('#this-one')

End result HTML

<img …>
<noscript id="not-this-one"><img …></noscript>

onload Function

You can hook an onload function for every loaded image

JS

loadMedia(null, function() {
   this.classList.add('loaded')
})

End result HTML

<img class="loaded" …>

Scroll-Based Loading

There's a default function to load images when they're scrolled into view.

This is a general solution, creating your own scroll-based loading functionality may be more performant.

Will be updated to use intersection observers when it becomes standardized.

JS

loadMedia(null, null, true)

Build

uglifyjs lazy-progressive-enhancement.js -m --comments > lazy-progressive-enhancement.min.js

Thanks

@agarzola, @raglannyc

-- MIT License (MIT)