Adriana Cota Adriana Cota - 1 year ago 51
Javascript Question

How can I preload an image to later set it as a background-image with jQuery?

I am trying to preload an image so when I need to set it as a background image, it's ready and it won't load during the CSS transition. I tried to do it using the AJAX load() method, but I think I should be able to do it without AJAX. I am not sure something like this would work since I don't need a img tag or src, but something like storing the direct URL of the background image so I can later set it as a background-image.

var img = new Image(); img.src = 'img.jpg';

This is what I've done so far:

$(document).ready(function() {
$('#LogoContainer').hover(function() {
$('#LogoMainPart').fadeTo('slow', 0.3);
$('#LogoOtherPart').fadeTo('slow', 1);
$('#Introduction').css('background-image', 'url(hoverbackground.jpg)');
}, function() {
$('#LogoMainPart').fadeTo('slow', 1);
$('#LogoOtherPart').fadeTo('slow', 0.3);
$('#Introduction').css('background-image', 'url(background.jpg)');

Answer Source

After creating the image object with

var myImage = new Image();

Assign the src of that image which will load the image into the browser cache like so:

myImage.src = 'my-bknd.jpg';

Now that it's in the browser cache you can add it to the DOM whenever you choose like so:

document.getElementById('myDiv').style.background = 'url(my-bknd.jpg)';