20

I have a web page that uses a large image for its background. I was hoping to use jQuery to load the image once it is downloaded (basically the way that bing.com loads its background image). Is this possible with jQuery? If so, is there a plugin that you would recommend?

JJJ
  • 32,902
  • 20
  • 89
  • 102
Villager
  • 6,569
  • 22
  • 65
  • 87
  • http://www.techerator.com/2010/11/how-to-make-a-css-background-slideshow-with-jquery/ works – TFD Aug 09 '12 at 02:05

4 Answers4

25

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');
Ian Boyd
  • 246,734
  • 253
  • 869
  • 1,219
Pim Jager
  • 31,965
  • 17
  • 72
  • 98
  • 6
    Thanks alot, but how can I make the background image fade in? – desbest Feb 09 '12 at 19:02
  • Here's one way. In document.ready:`$('').attr('src', url).load(function(){ $('#yourContainerDiv').css('backgroundImage', 'url('images/yourImage.png')' ); $('#yourContainerDiv').fadeIn('slow'); }); });` Apologies for the formatting. Paste in your editor to read it. No code blocks allowed in comments. – Jeremy Penrod Oct 06 '12 at 00:47
11

This article may be useful. Copying from there:

HTML

<div id="loader" class="loading"></div>

CSS

DIV#loader {
  border: 1px solid #ccc;
  width: 500px;
  height: 500px;
}

/** 
 * While we're having the loading class set.
 * Removig it, will remove the loading message
 */
DIV#loader.loading {
  background: url(images/spinner.gif) no-repeat center center;
}

Javascript

// when the DOM is ready
$(function () {
  var img = new Image();

  // wrap our new image in jQuery, then:
  $(img)
    // once the image has loaded, execute this code
    .load(function () {
      // set the image hidden by default    
      $(this).hide();

      // with the holding div #loader, apply:
      $('#loader')
        // remove the loading class (so no background spinner), 
        .removeClass('loading')
        // then insert our image
        .append(this);

      // fade our image in to create a nice effect
      $(this).fadeIn();
    })

    // if there was an error loading the image, react accordingly
    .error(function () {
      // notify the user that the image could not be loaded
    })

    // *finally*, set the src attribute of the new image to our image
    .attr('src', 'images/headshot.jpg');
});
kgiannakakis
  • 103,016
  • 27
  • 158
  • 194
1

You can't use CSS background images, because it's impossible to attach an event to the loading of the images (as far as I know).

So I'll give it a shot, but haven't tested it:

HTML:

<body>
<div class="bgimage"><img src="/bgimage.jpg" ></div>
<div>
  ... content ...
</div>
</body>

CSS:

.bgimage { position: absolute: }

Javascript:

$(function() {
   $(".bgimage")
      .css("opacity",0);
      .load(function() { $(this).fadeIn(); });
});
Philippe Leybaert
  • 168,566
  • 31
  • 210
  • 223
-2

You can go with the following trick, sorry if its a bit dirty.

Script :

        jQuery.preloadImages = function() {
        for (var i = 0; i < arguments.length; i++) {
            jQuery("<img>").attr("src", arguments[i]);
            $('.box1').attr('preloadURL', arguments[0]);
        }
    }

    $.preloadImages("sky.jpg");

    $(document).ready(function() {
        if ($('.box1').attr('preloadURL') == 'sky.jpg') {
            $('.box1').css({ 'background-image': 'url(sky.jpg)' },$('.box1').fadeIn(1000));
        }
    });

Markup :

<div class="Content">
        <label>Search Bing</label>
        <input type="text" />
        <input type="button" value="search" />
    </div>
<div class="box1"></div>

css:

.box1 {background-repeat:no-repeat; width:800px; height:600px; display:none; position:relative;}
    .Content { position:absolute; left:20px; top:20px; z-index:100;}
    .Content label { color:White;}

hope this helps

A little sample on : http://xgreen.co.uk/test.htm

Ali
  • 253
  • 1
  • 4