title: Preload CSS background images for jQuery plugin
body: <p>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)</p>
  
  <p><a href="http://jacob-king.com/demo/speedometer" rel="nofollow noreferrer">http://jacob-king.com/demo/speedometer</a></p>
  
  <p>I tried using <a href="https://stackoverflow.com/questions/1787319/preload-hidden-css-images">this solution</a>, which solves the issue of the "broken" image preloading:</p>
  
  <p><a href="http://jacob-king.com/public/notSoPublic/jquery.speedometer-1.0.3/example.html" rel="nofollow noreferrer">http://jacob-king.com/public/notSoPublic/jquery.speedometer-1.0.3/example.html</a></p>
  
  <pre><code>(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&lt;=1; i++) 
       {
            imageObj.src=images[i];
       }
  
  })();
  </code></pre>
  
  <p>But how do I force the plugin to wait for both background images to load before starting the animation?</p>
  
  <hr>
  
  <p><strong>Solution</strong></p>
  
  <p>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.</p>
  
  <p>I ended up going with a slightly modified version of crimson_penguin's solution:</p>
  
  <pre><code>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.
      });
  });
  </code></pre>
  
  <p>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 <a href="http://jacob-king.com/public/notSoPublic/jquery.speedometer-1.0.3/example.html" rel="nofollow noreferrer">here</a>, and I'll be including it as part of my 1.0.4 update. Thanks, everyone.</p>
  
  <hr>
  
  <p>Edit: I spoke too soon. Without the images loaded into cache, the plugin fails to start on the first page load in Google Chrome...</p>