Sunrise in the fog

    Revisiting Lazy Loading

    I've previously written on a lazy loading implementation I'd made, but that was before I found intersection observers. Since then, I've built a full NPM package for adding lazy loading, both for images or any other element/content.

    Before we get into using intersection observers for lazy loading, I should explain what they are. They're a type of observer that detects when an element comes into or leaves the viewport. Pretty simple right? It's a native API with pretty good support, I.E. is the only thing you may need to worry about adding in graceful degradation. Essentially, when using an intersection observer, we create our observer, and then have it observe elements on the page. The observer will, on the elements it's watching entering or exiting the viewport, invoke a callback defined in the creation of the observer. Here's a basic example.

    As you've probably guessed, a native API for detecting when something enters the viewport solves lazy loading. We can set up an observer to watch elements on a page and, when they enter the viewport, set their source attribute (assuming they are an image).

    While we could create an implementation to do this, I've already got one up on NPM. It allows for setting up image lazy loading just by adding an attribute ("io-img-src” or "io-img-srcset”) and then calling the package's setup function. Here's an example:

    [gist src=https://gist.github.com/benrgreene/0652cbf7ed2a995f810cfe2fd2c5993f file=template.html][/gist]

    [gist src=https://gist.github.com/benrgreene/0652cbf7ed2a995f810cfe2fd2c5993f file=lazyload.js][/gist]

    There's a couple parameters for setting our own query string for what elements to watch, as well as the callback for when they come into view:

    [gist src=https://gist.github.com/benrgreene/0652cbf7ed2a995f810cfe2fd2c5993f file=lazyload-parameters.js][/gist]