Last active
March 15, 2024 13:42
-
-
Save enyo/5697533 to your computer and use it in GitHub Desktop.
Preloading images with jQuery
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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