One popular strategy to improve the website performance is to not load images until they enter the viewport – aka "lazy-loading images".
srcattribute of an
imgtag in favor of lazy-loading, make sure you have a strategy to serve crawlers, if you need to support them.
- When the lazy-loaded image in inserted into the page, it may push other elements down to get the space it needs. Prevent a jumpy user experience by giving the image container the dimensions of the image.
- Mobile devices usually trigger the
onscrollevent only when the "momentum scroll" has ended. This way you may coast into parts of the page where images have not been loaded yet (depending on the library). (Starting from iOS 8, continuous scroll events are fired.)
- it automatically notices when images should be loaded, thus it works with sliders, lightboxes and almost anything; this feature is really amazing and makes this library stand apart from others. It is achieved by registering to a dozen events plus using a MutationObserver, if available.
- the author seems to be really eager to maintain the library
- it requires no configuration (just include it to your page), but offers a powerful API
- it was written to be performant, with little runtime as well as memory consumption; it promises to be jank-free, rendering at 60fps
- it features a plugin system, bringing 14 plugins out of the box
- noscript plugin: support for non-JS browsers, i.e. crawlers
If you need to react on image load, e.g. to update some slider layout, just listen for the event:Copy
$('.some-element').get(0).addEventListener('load', yourCallBack, true);
trueregisters the listener to the "capturing phase" (as opposed to the "bubbling phase"). This is because the
loadevent does not bubble. Note that you cannot register an event listener via jQuery, as it does not support capturing events. That's why that
JS-only: not working
The "best" strategy would be to hide the
All working lazy-load strategies require the
src attribute of images to be removed (see above). Filling it back in via JS is ok for most users, but crawlers won't see your images. One approach is to render the image a second time into a
noscript tag. This is quite straightforward and most people on the web agree that it won't negatively influence SEO ranking.