Preload all images in a directory using jQuery

Rafael Adel picture Rafael Adel · Sep 9, 2012 · Viewed 7.5k times · Source

I want to preload all images in a directory called img,and that directory also contains sub directory called ui_images.

I know how to preload specific images by putting their names in an array and doing the preloading work, but i want to know how to tell the script to search dynamically for all images in that directory img and img/ui_images?

Here's my code :

var preloadImg = function(imgArr){
    $.each(imgArr, function(index,value){
        $("<img/>")[0].src = value;
    }); 
}

var arrimg = ['img/check.png','img/add_sub.png'];
preloadImg(arrimg);

Answer

jfriend00 picture jfriend00 · Sep 9, 2012

There is no generally available facility for doing a directory listing in http. The options I can think of are:

  1. Name your images in a predictable fashion like (img001, img002, etc...) and then you can load images until you get an error.

  2. Name your images in a predictable fashion like (img001, img002, etc...) and then code in one numeric limit value into your web page for how many there are.

  3. Create an ajax call (on both client and server) that will give you a list of image names to preload.

  4. Have your server embed an array of image names into the page so you know what to preload.