Defer Image Loading until Scrolled-To (Lazy-Loading)
Works in modern browsers and IE9+
Please view the source of this page for HTML markup and JS.
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="" />
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
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;
- A throttle to limit how often the elementFromTop() function executes while scrolling.
- A debounce to recalculate window height and fire the elementFromTop() function after a window resize event.
More demos and snippets
Did you find this useful? There are more demos and code snippets this way.