• Stars
    star
    190
  • Rank 203,739 (Top 5 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 8 years ago
  • Updated over 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

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

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

  • 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

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)