Defer Image Loading until Scrolled-To (Lazy-Loading)

A demo that combines my Add Class to Target-Element when Trigger-Element is Scrolled into View elementFromTop() JavaScript function with Patrick Sexton's defer image script, to make simple lazy-loading images.

Works in modern browsers and IE9+

Please view the source of this page for HTML markup and JS.

Scroll Down...

The pic below is a standard <img> with the usual src="" attribute. Nothing special going on there...

Image 1 - Standard <img>

The next 3 images have deferred loading, so they're only downloaded once they're scrolled-to.

Their src="" points to a base64 data URI of a transparent gif, while their real image path resides inside a "data-src" attribute.

<img class="img-defer" data-src="real-image.jpg" src="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==" alt="" />

They're identified and triggered by the "img-defer" class, which is passed to the elementFromTop() JavaScript function.

When the elementFromTop() scroll distance is met, the "img-defer" class is replaced with the "img-load" class. The imgDefer() function uses this to load in the real image by switching the img tag's "data-src" attribute to "src".

Image 2 - Deferred Load

Image 3 - Deferred Load

Image 4 - Deferred Load

JavaScript Performance Considerations

Because this is a scroll-activated script, the rate at which the function fires has the potential to be very high.

Attaching functions directly to the scroll event is usually a bad idea; Scrolling using a trackpad, scroll wheel, or just by dragging a scrollbar can easily trigger 30 events per second. Scrolling on a smartphone can trigger significantly more.

This script takes performance into consideration by using;

"Debouncing" and "throttling" help improve performance by controlling the effect of potentially expensive JavaScript functions that may otherwise cause a page to become unresponsive when fired repeatedly. Please see the Debouncing and Throttling Explained Through Examples article at CSS Tricks for further information.


More demos and snippets

Did you find this useful? There are more demos and code snippets this way.