Preload Images with JQuery

In a recent project I had an image heavy page and noticed that sometimes, certain images would not load for some reason. I used the technique found here to ensure that my images were being loaded.

I created a quick file named preload_images.js and put the following into it.

(function($) {
  var cache = [];
  // Arguments are image paths relative to the current page.
  $.preLoadImages = function() {
    var args_len = arguments.length;
    for (var i = args_len; i--;) {
      var cacheImage = document.createElement('img');
      cacheImage.src = arguments[i];
      cache.push(cacheImage);
    }
  }
})(jQuery)

Then in my themes .info file, I added the following

scripts[] = js/preload_images.js

Next, I added this to my page.tpl.php in the head section

<script type="text/javascript">
jQuery.preLoadImages("/images/home-menu-block.png", "/images/button-about.png");
</script>

Then a simple visit to the performance page mysite.com/admin/settings/performance to clear the cache.
That seemed to do the trick, no more missing images!

Contact Me

Feel free to contact me.

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.