Image Preloading with jQuery

April 28th, 2011 | by | jquery, web development

Apr
28

jQuery - Write Less do More

Recently, I had to make some modifications to a site that was designed and built back in 2004 when you required to make things look nice,
I noticed that there were way to many images being loaded due to hover effects, rounded corners, etc, etc, etc. Which caused the site to load
slowly. I personally am of the school that if the web site does not open within 5 seconds, I’m already looking for another website. So to help
with this problem I went ahead and wrote a small with . Since this website was built along time ago, I did not remember
the id’s or classes of the images that were being loaded so I created a reusable jQuery function that is reusable to load images as I found them.

Save the script below as jquery.preloadImages.js
And remember to include it before you call the function.

View Code JAVASCRIPT
/**
 *
 *	Preloads Images using jQuery, Can load unlimited amount of images to Cache.
 *
 * Usage is as followed
 *
 *  jQuery.preloadImages("image1.jpg", "image2.jpg",…,"image7.jpg");
 *
 *	Since this function accepts unlimited arguments you can use it again and again no matter how many images you need to preload.
 *
 *	
 * Copyright (c) 2011 Shawn Crigger (http://s-vizion.com)
 * Licensed under the MIT License (LICENSE.txt). 
 *	Created by Shawn Crigger <shawn@s-vizion.com>
 *
 **/
(function ($)
 {
  var cachedimages = [];
  $.preloadImages = function()
  {
    var i   = 0;
    var num = arguments.length;
    for ( i = num; i--;)          
    {
      var thisImage = document.createElement('img');
      thisImage.src=arguments[i];
      cachedimages.push(thisImage);
    }
  }
})(jQuery)

Basicly, to call this function just copy paste the following code and save the above file.

View Code JAVASCRIPT
<script type="text/javascript">
 
  $(window).ready(function()
  {
    jQuery.preloadImages("image1.jpg", "image2.jpg","image7.jpg");
  }
 
</script>
Tags: , , , , , ,

Authored by

I am a CPU Commando, I work hard to destroy the evil Bill Gates plan's for Global Computer Control and follow Linus Torvalds teachings of Open Source OS's and Free Software ( Free as in Speech not Beer ) When I'm not teaching the world to use Linux then I am trying to teach people proper Web Programming and maybe a little Hacking Aside. If you're reading this on Internet Explorer v?? then your CPU will explode in 10 seconds, your wife will leave you, your dogs will die and your pickup truck will run off a Cliff all on your way to pickup your Mama from the Pen.