There\'s tons of articles of how to preload an image, however I can\'t seem to find anything useful about preloading a background image with jquery.
I made a simple
You can't as long as it's a background image. Load it normally and then set the background image. Something like this:
var $img = $( '<img src="' + src + '">' );
$img.bind( 'load', function(){
$( '.yourDiv' ).css( 'background-image', 'url(' + src + ')' );
} );
if( $img[0].width ){ $img.trigger( 'load' ); }
the last line is needed in some browser in case the image is cached.
You logic is almost good, but you can not catch events for CSS in jquery.
You need to load the background image to some <img>
element. Catch the event load of that element and when it's fired you change the background image to that src and do the rest of your logic.
A working example with a mock setTimeout
to simulate loading time.
The relevant jQuery code is:
$('#LOADING-SIGN-DIV').fadeOut();
$('#DIV-THAT-NEEDS-PRELOADING').fadeIn();
To do the preloading, why not grab the URL from the css
attribute with jQuery? Something like this:
var bg_url = jQuery("#DIV-THAT-NEEDS-PRELOADING").css('background-image');
// using regex to replace the " url( ... ) "...
// apologies for my noobish regex skills...
bg_url = str.replace(/ /g, '', bg_url); // whitespace...
bg_url = str.replace(/url\(["']?/g, '', bg_url); // next, the 'url("'...
bg_url = str.replace(/["']?\)/g, '', bg_url); // finally, the trailing '")'...
// without regex, using substring if confident about no quotes / whitespace...
bg_url = bg_url.substring(4, bg_url.length-1);
// preloading...
var img = new Image();
img.onload = function()
{
// do transitions here...
};
img.src = bg_url;
Here's a post from last week that covered preloading images with jQuery: HTML 5 File load image as background-image
And here is the solution that post referenced: http://sveinbjorn.org/dataurls_css