Question

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);
Was it helpful?

Solution

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.

OTHER TIPS

I was looking at improving the performance on one of my sites and looked into this. My solution seems to work and I haven't seen it anywhere else yet.

Its a two step approach using jquery and php

  1. // Preload images via jquery .load and delete once their cached via the callback

    <div id="preload"></div>
    
    $('#preload').load('preload.php', function() {   
    $('#preload').remove();   
    });
    
  2. // preload.php below - loop through the image folder and insert the images into a hidden div

    <div style="display:none">
    <?php
    $dirf = 'images';
    $dir  = scandir($dirf);
    foreach ($dir as $file) {
    if (($file != '..') && ($file != '.')) {
        echo "<img src='images/$file' />";
        }
    }
    ?>
    </div>
    

This worked in Firefox but feel free to critique or improve

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top