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
srcset
images.Other lazy loaders promote invalid HTML by omitting the src attribute, or aren't compatible for users without javascript.
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!" …>
You can specify what images to load by passing in either
DOMContentLoaded
)noscript
s (from something like document.querySelectorAll
)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>
You can hook an onload function for every loaded image
JS
loadMedia(null, function() {
this.classList.add('loaded')
})
End result HTML
<img class="loaded" …>
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)
uglifyjs lazy-progressive-enhancement.js -m --comments > lazy-progressive-enhancement.min.js