Author: | quru |
---|---|
Views Total: | 536 views |
Official Page: | Go to website |
Last Update: | June 16, 2017 |
License: | MIT |
Preview:

Description:
image-defer.js is a JavaScript library that smartly defers the loading of images to reduce the page load time and improve the UX. Licensed under the GNU Affero General Public License v3.0.
How it works:
- If you scroll down in your web browser they should load on-demand when you scroll slowly or stop scrolling. Image loading should be skipped while you are scrolling quickly.
- When the image limit is reached, images that are off-screen should start reverting back to their initial placeholder, from the top if you are scrolling down, or from the bottom if you are scrolling up.
- If you resize the window (or rotate your device) so that the page layout and scroll position changes, any newly visible images should load, and the limit should be re-evaluated.
- If the number of visible* images exceeds the limit, the limit will be exceeded.
How to use it:
Include the main JavaScript ‘image-defer.js’ on the webpage when needed.
<script src="/path/to/image-defer.js" defer></script>
Add the placeholder to the webpage and define the original image in the ‘data-defer-src’ attribute as this:
<img class="defer" src="placeholder.png" data-defer-src="original.jpg">
Pre-define ImageDefer when using ‘async’ or ‘defer’ with <script>:
window.ImageDefer = window.ImageDefer || {};
Set the image-defer options:
ImageDefer.options = { onImageRequested: imageLoading, onImageLoaded: imageLoaded, onImageUnloaded: imageUnloaded };
Respond to image-defer events:
function imageLoading(img) { removeClass(img, 'loaded'); addClass(img, 'loading'); } function imageLoaded(img) { removeClass(img, 'loading'); addClass(img, 'loaded'); } function imageUnloaded(img) { removeClass(img, 'loading'); removeClass(img, 'loaded'); }
All default options and callback functions.
ImageDefer.options = { // the maximum number of images to lazy load before starting to unload images again maxLoaded: 100, // the time to wait, in milliseconds, before considering that a scrolling event has completed scrollingStopMillis: 500, // the speed of scrolling, in pixels/millisecond, above which images will not be lazy loaded scrollingSkipRate: 0.8 // callback functions onImageRequested: null, onImageLoaded: null, onImageUnloaded: null, };