Fading in a background image

You could first load the image, and then, when it has finished loading, set it as background-image. That way the browser will (hopefully) load the background image from the cache instead of redownloading it. As you requested it as a plugin:

 $.fn.smartBackgroundImage = function(url){
  var t = this;
  //create an img so the browser will download the image:
  $('<img />')
    .attr('src', url)
    .load(function(){ //attach onload to set background-image
       t.each(function(){ 
          $(this).css('backgroundImage', 'url('+url+')' );
       });
    });
   return this;
 }

Use it like this:

 $('body').smartBackgroundImage('http://example.com/image.png');

Leave a Comment