ImageLoader Class
Initiates the asynchronous loading of image files by the browser. Useful to start preloading images rather than waiting to do it as the browser encounters them during the rendering of the page.
The class maintains a list of images to load. As each image is loaded, it is removed from the list. If an image fails to load, it remains in the list until the client explicitly re-attempts to load it.
Typical Usage
var image_loader = new ImageLoader();
image_loader.queueImage("http://myserver.com/media/header.png");
image_loader.queueImage("http://myserver.com/media/location_map.png");
image_loader.loadAll(
function(success) {
if( success ) {
console.log("Image was successfully loaded." );
} else {
console.log("Loading failed for image." );
}
console.log("Remaining images: " + image_loader.getImageList() )
}
);
Constructor
ImageLoader
()
Item Index
Methods
createImage
()
private
A wrapper provided for testing purposes.
Returns:
A new Image object.
getImageList
()
Returns:
A list of images that are currently queued for loading.
initNewImage
-
[event_handler]
Utility method invokes createImage() to create an element, then attaches the supplied callback to the element's onload property, wrapped with some logic to remove the URL from the queue following a successful load.
If onload is invoked, the callback is called with an argument of true. If onerror is invoked, the callback is called with an argument of false.
Parameters:
-
[event_handler]
Function optionalThe callback function.
Returns:
The newly created element.
loadAll
-
[event_handler]
Invokes loadImage() once for each image URL in the current queue.
A callback function may be supplied which will be invoked whenever an image loads or fails to load. The function should receive a single boolean argument which is a flag indicating whether loading was successful or not.
Parameters:
-
[event_handler]
Function optionalThe optional callback function.
loadImage
-
[src]
-
[event_handler]
Loads a single image resource from the given URL.
A callback function may be supplied which will be invoked when the image loads or fails to load. The function should receive a single boolean argument which is a flag indicating whether loading was successful or not.
If loading is successful and the given URL is found in the queue, it is removed. Otherwise the URL is left in the queue and can be re-tried later by another call to loadImage() or loadAll().
Parameters:
-
[src]
String optionalURL of the image resource to load.
-
[event_handler]
Function optionalThe optional callback function.
Returns:
The newly created element.
queueImage
-
src
Adds an image URL to the queue, to be loaded later by a call to loadAll().
Parameters:
-
src
StringThe URL of the image resource to queue.