title: jquery for preloading a set of background-images
body: <p>My google-fu is failing me on this one.  I have an html page with a series of divs like the one below interspersed among other html:</p>
  
  <pre><code>&lt;div class="featureImage" style="background-image:url('defaultBackground');"&gt;
  &lt;a href="linkHere" style="background:url('realBackground') no-repeat center center;"&gt; &lt;/a&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>I find that these feature images (realBrackground) are not being preloaded so they only load up when the tab that displays them shows up.  What I'd really like to do is have jquery preload them in the background after the page is rendered document.ready() so that when the user clicks on another tab the display of the feature image is instantaneous, but the load won't slow down the initial page display.</p>
  
  <p>The jquery selector I got worked out was <code>$(".featureImage &gt; a").css("background-image")</code> but how could I code that up so that it would go through and find all instances of that, and actually preload the image after the page has rendered?</p>
  
  <p><strong>UPDATE:</strong></p>
  
  <p>I got the answer figured out with help from <a href="https://stackoverflow.com/questions/9847012/preloading-jquery-images/9847168#9847168">Preloading jquery images</a> and <a href="http://blog.webmonkey.uk.com/2009/07/jquery-quick-tip-extract-css-background-image/" rel="nofollow noreferrer">jQuery Quick Tip: Extract CSS Background Image</a></p>
  
  <p>The key was that the .css selector only works on the first match it finds, which is what had been giving me fits. Here is what I came up with, I would love to have improvements!</p>
  
  <pre><code>&lt;script&gt;
  
  function extractUrl(input)
  {
   // remove quotes and wrapping url()
   return input.replace(/"/g,"").replace(/url\(|\)$/ig, "");
  }
  
  function preloadImages(list) {
      var img;
      if (!preloadImages.cache) {
      preloadImages.cache = [];
  }
  for (var i = 0; i &lt; list.length; i++) {
      img = new Image();
      img.src = list[i];
      preloadImages.cache.push(img);
  }
  }
  jQuery(document).ready(function() {
  
         var items = new Array();
         $(".featureImage &gt; a").each(function() {
         items.push(extractUrl($(this).css("background-image")));});
         preloadImages(items);
  
  });
  &lt;/script&gt;
  </code></pre>
  
  <p>tl;dr: I Had to break my selector into two and use the each() function to walk through and find all the items I wanted and extract the urls and push it into an array. After I had the array, previous stack overflow answers got me the rest of the way.</p>