Skip to content

Instantly share code, notes, and snippets.

Last active Dec 18, 2015
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.src = src;
// Example usage:
var $body = $(body);
var backgroundImage = "/imag/background.jpg";
preload(backgroundImage, function() {
$body.css({ backgroundImage: "url(" + backgroundImage + ")" });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment