Background image preload

There are tons of articles on how to preload an image, however I can't find anything useful in preloading a background image using jquery.

I made a simple html layout of what I would like to achieve: http://jsfiddle.net/3rfhr/

  • The download window will appear.
  • Background loaded
  • Loading div disappears
  • Background div will appear

I can handle div transitions, but I don't know how I need to preload the css background. Thanks for reading my question :)

+8
javascript jquery css
source share
6 answers

You cannot if this is a background image. Download it normally and then set the background image. Something like that:

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 necessary in some browsers in case of image caching.

+7
source share

To preload, why not grab the url from the css attribute using jQuery? Something like that:

 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; 
+2
source share

Here's a post from last week that covered pre-loading images using jQuery: HTML 5 Image upload file as background image

And here is the solution referenced by the links: http://sveinbjorn.org/dataurls_css

+2
source share

You logics are almost good, but you cannot catch events for CSS in jquery.

You need to load the background image into some <img> element. Catch the load on the event of this element, and when it is fired, you change the background image to this src and execute the rest of your logic.

+1
source share
+1
source share

A working example with setTimeout layout to simulate load time.

Relevant jQuery code:

 $('#LOADING-SIGN-DIV').fadeOut(); $('#DIV-THAT-NEEDS-PRELOADING').fadeIn(); 
0
source share

All Articles