Preload with jQuery

Recently i wrote an article on understanding preloading and right after completed writing that article, I'm on my journey to create a jQuery gallery for a project. At that time, i found an interested method written by Matt on preload with jQuery. And i think this should be adopt by many programmers out there. But basically, he creates a preload function for jQuery as shown below

jQuery.preloadImages = function()
  for(var i = 0; i<arguments.length; i++)
    jQuery("<img>").attr("src", arguments[i]);

So, once your jQuery is ready, we will fire up preload function as shown below,

$.preloadImages("image1.gif", "/path/to/image2.png","some/image3.jpg");

Pretty neat right? But for me to add these path one by one into the preload function is not my kind of meat. So i will prefer the following code which also takes in array into consideration

jQuery.preloadImages = function() {
var a = (typeof arguments[0] == 'object')? arguments[0] : arguments;
for(var i = a.length -1; i > 0; i--) 
	jQuery("<img>").attr("src", a[i]);

And i will use it like this,

var images = [];

basically it retrieves all the images with class .box and placed into an array to be preloaded. Why do i want it to take in an array instead? Because i don't use image tag such as

<img src="image1.gif"/>
<img src="image2.png"/>
<img src="image3.png"/>

instead i usually gallery it like this,


The reason is it loads up faster. And all bandwidth will be dedicated to load up the page instead of distributing some to the images that might not be showing out yet. There are also many advantages and disadvantages of doing this but let's keep it this way. Furthermore, the images are usually populated by server which resist in HTML. It is always good to have alternative!


One thought on “Preload with jQuery

Comments are closed.