pre-loader
Event-driven sequential image preloading and lazyloading in vanilla js.
Installing
Either download it
...or, clone the repo:
$ git clone https://github.com/DimitarChristoff/pre-loader.git...$ cd pre-loader
...or use bower:
$ bower install pre-loader --save
Basic use
Load an array, get a functional callback when done:
// under a normal browser/*Array*/images /*Object*/options/; // AMD with requireJS;
NOTE: if RequireJS or any other AMD-compatible loader is available, pre-loader will not go to the global object but define itself as an AMD module that can be required.
Options
The options
object you can pass to the constructor supports 5 different keys.
{
// use a single pipeline, default: false
pipeline: false,
// auto start loading when instantiated
auto: true,
// optional function to call on each image
onProgress: function(src, imageEl, index){},
// optional function to call when all done
onComplete: function(loaded, errors){},
// optional function to call when an error happens
onError: function(src){}
};
Example
The most basic example to prime the cache with 2 images:
'image1.jpg' 'http://domain.com/image2.jpg' { console; errors && errorslength && console; };
Progress reporting
Loading an array of images, firing a callback with each one and in the end:
'image1.jpg' 'http://domain.com/image2.jpg' { if element consolelog|'loaded ' + src; // gets optional reference to element you can use: // document.appendChild(element); else console; // output some stats var donePercent = Math; console; } { console; errors && errorslength && console; };
Pipeline vs parallel
Optionally, you can control how the loading takes place. You can either let the browser resolve the resource handling or you could stick to using a single thread with pipelining (each image that completes calls the next one in the stack).
'image1.jpg' 'http://domain.com/image2.jpg' // enable a single pipeline pipeline: true { // this will take longer but won't waste resources. };
Waterfall with pipeline enabled:
Waterfall with parallel downloading enabled:
For more info, see the example
folder or look at http://jsfiddle.net/dimitar/mFQm6/
Lazy loading of images
Lazy loading works based upon existing DOM img elements with a data-preload
attribute, pointing to the image to load.
eg.
The lazyLoad
method accepts arguments to the normal preLoader
constructor and additionally, a selector
property
that defaults to img[data-preload]
. It will return an instance and all the callbacks will fire as expected. When
an image matches the DOM element, it will set the src
property and remove the data-preload
attribute.