Skip to content

Instantly share code, notes, and snippets.

@enyo
Last active Dec 18, 2015
Embed
What would you like to do?
Preloading images with jQuery
/**
* Preloads the image, and invokes the callback as soon
* as the image is loaded.
*/
var preload = function(src, callback) {
// Create a temporary image.
var img = new Image();
// Invoke the callback as soon as the image is loaded
// Has to be set **before** the .src attribute. Otherwise
// `onload` could fire before the handler is set.
$(img).load(callback);
img.src = src;
};
// Example usage:
var $body = $(body);
$body.addClass("loading-background");
var backgroundImage = "/imag/background.jpg";
preload(backgroundImage, function() {
$(body).removeClass("loading-background");
$body.css({ backgroundImage: "url(" + backgroundImage + ")" });
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment