lazy-progressive-enhancement
lazy-progressive-enhancement copied to clipboard
A lazy image loader designed to enforce progressive enhancement and valid HTML.
Lazy Progressive Enhancement
Download, copy-paste, whatever ;)
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
- Designed to enforce progressive enhancement and valid HTML.
- Written in pure JS -- no dependencies.
- Not a framework, not a library, just a function.
- Works with responsive
srcset
images. - Works with iframes.
Other lazy loaders promote invalid HTML by omitting the src attribute, or aren't compatible for users without javascript.
Contents
- Basic Usage
- Load Specific Images
- onload Function
- Scroll-Based Loading
- Build
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
- A CSS selector string (use if calling the function before
DOMContentLoaded
) - A NodeList of
noscript
s (from something likedocument.querySelectorAll
) - A singular
noscript
Element (from something likedocument.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
-- MIT License (MIT)