views:

31

answers:

2

I've written this simple image preloader based on my knowledge of javascript, but I don't know if it will actually load the images before the page is displayed or if it will still load the images.

   function preloadImages(html) {   
for(var i=0;i<document.images.length;i++) {
    img_obj = new Image();
    img_obj.src = document.images[i].src;
    if (!img_obj.complete) alert("could not load:" + img_obj.src);
    else continue;
}   
   $("#pad").fadeIn(200);
   return true;
}

In addition, is it correct the way I preload the images?

A: 

Depending on what you want to do. The js should run onload which is after the page has loaded so I am not sure you really get any benefit. (http://dean.edwards.name/weblog/2005/02/order-of-events/)

You can do preloading using CSS.

matpol
I use an ajax call to load the pages into a div container, so within my actual function that loads and handles the ajax request I use this?
Ferdi
I probably wouldn't really call this preloading then as you are only loading them when you call the ajax function. Generally if I am doing a whizzy kind of thing I will load everything into the page first then hide it. Then I know everything is loaded and accessible and then I start doing whizzy stuff with it e.g. slideshows etc.
matpol
+1  A: 

To load the image the image needs to have a height/width on the page.

I think most people commonly insert the image into DOM, setting a height, width, making sure display is block. Set an absolute position at -9999px left and top, or something along those lines. The images will be cached for when you need them.

Mark