It’s almost three months ago since my last post! I’m quite busy at the moment. That’s why I’ll just write a quickie on delayed image preloading using Mootools (1.2.1, also might work with 1.2 and 1.1).

Image preloading

Most of the times you’ll need preloading when there are elements in the DOM that are hidden, but have an image background. On the moment the elements are shown and the images are not found in cache, the images are loaded from the server. This action has a small delay, so your element first shows up without the image background. That might confuse the visitor.

Note that there are other possible scenario’s that need image preloading, but this case is a nice introduction.

Delaying image preloading

Why in the world would we like to delay the preloading of the images? Well, most browsers only allow two concurrent requests at the same time to the same domain (correct me if I’m wrong). When we do the image preloading on domready, it might hold up other resources that need to be loaded. Because we preload images that are not shown when the page loads, we can delay the preloading.

The javascript

Let’s say we have a total of five images that need to be preloaded. Here’s how I would preload the image, 3 seconds after the dom is ready:

Array.each.delay(3000,this,[
	['foo.gif', 'bar.png','moo.png','tools.png', 'mootools.png'],
	function(src){var img = new Image();img.src = src;}
]);

Easy huh? It delays a call to Array.each by 3000 ms. Then it passes the array of images as the first argument, and the function as the second. You can read more about delay at the Mootools Docs.