With Ajax being all the rage, preloading images has become somewhat important. The problem is, loading them with all the other page components adds to the load time and it may not even be used. Enter preloadImage — a function set to stop all that. It’s very simple but can be used to powerful means:
var preloadImage = function(url, callback) {
var image = new Image();
image.src = url;
image.onload = image.onabort = image.onerror = callback;
return image;
};
Just specify the URL (url) and the callback function (callback) as so:
var callback = function(e) {
alert(e.type);
};
var image = preloadImage('http://www.sidroberts.co.uk/image.gif', callback);
On the load event, the abort event or the error event, the callback function will be executed. You can distinguish these with the type property which is "load", "abort" and "error" respectively.
Now any image that points to that URL will load almost instantly.
Comments
No responses have been made so far. Add your comments.