[Reduced] 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
Related
More demos and snippets
Did you find this useful? There are more demos and code snippets this way.