Skip to content

Instantly share code, notes, and snippets.

@enyo
Last active March 15, 2024 13:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save enyo/5697533 to your computer and use it in GitHub Desktop.
Save enyo/5697533 to your computer and use it in GitHub Desktop.
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