Jake
Jake

Reputation: 4899

Preload CSS background images for jQuery plugin

I have a jQuery plugin that uses a needle gauge. Upon initially loading a page containing the plugin, the plugin begins its animation before the background image has loaded. A second image (a "broken" gauge) loads when the speedometer goes out of range, but again there is a delay before the image loads. (to see this, enter a value lower than zero or higher than 100)

http://jacob-king.com/demo/speedometer

I tried using this solution, which solves the issue of the "broken" image preloading:

http://jacob-king.com/public/notSoPublic/jquery.speedometer-1.0.3/example.html

(function(){

     // counter
     var i = 0;

     // create object
     imageObj = new Image();

     // set image list
     images = new Array();
     images[0]=_speedometerDirectory+"/background.jpg";
     images[1]=_speedometerDirectory+"/background-broken.jpg";

     // start preloading
     for(i=0; i<=1; i++) 
     {
          imageObj.src=images[i];
     }

})();

But how do I force the plugin to wait for both background images to load before starting the animation?


Solution

Since the images were loaded as part of the jQuery plugin, placing them outside the $.fn call seemed inappropriate; the images shouldn't load unless the speedometer function is invoked.

I ended up going with a slightly modified version of crimson_penguin's solution:

var img0 = new Image();
img0.src = _speedometerDirectory+"/background.jpg";
var img1 = new Image();
img1.src = _speedometerDirectory+"/background-broken.jpg";

$(img0).load(function() {
    $(img1).load(function() {
        // Everything's ready. Now we begin.
    });
});

This probably looks a little kludgy. Feel free to suggest a more elegant syntax (It's late and I'm tired, and this works, so "Good Enough"). The result can be seen here, and I'll be including it as part of my 1.0.4 update. Thanks, everyone.


Edit: I spoke too soon. Without the images loaded into cache, the plugin fails to start on the first page load in Google Chrome...

Upvotes: 1

Views: 1930

Answers (2)

crimson_penguin
crimson_penguin

Reputation: 2778

You're only using one object to load both images; I'm not sure that will work. I would instead do something like this:

for(i=0; i<=1; i++) 
{
     var img = new Image();
     img.src = images[i];
     images[i] = img;
     $(images[i]).load(function() { ... });
}

Then you can set that load function there to decrement (or increment) some count variable, and when it reaches zero (or the number it's supposed to reach), you start. The count variable will have to not be local to that for loop of course. I'm not sure if it has to be global or if it could be local to the function.

Upvotes: 1

Raynos
Raynos

Reputation: 169401

window.onload = function() {
    // start my plugin
};

Window.onload should only trigger after images have loaded. For safety I would run your image precaching function in the head.

Upvotes: 1

Related Questions