Skip to content


How to Preload an Entire Directory of Images Using Javascript and PHP

Why Preload?

The main reason you want to preload images is when they are being used for mouse-over or roll-over effects. If they're not displayed by the page when it loads then the page will wait until the image is needed to load it. However, this can result in a delay to the mouse-over/rollover effect while the image loads. In steps the preload.

Before we dig into how this works, I'll provide the finished code for those who just want to copy and paste. As always, click the "PLAIN TEXT" above the code to view it in a copy & paste friendly format. For those who want to know how it works, read on.

PHP:
  1. //This function will cycle through the directory it is sent
  2. //$x is used to count the number of images, we set it to 0 by default
  3. function preloadImages($directory, $x = 0) {
  4.     //first, lets make sure the user sent a directory.  If they didn't, return "false"
  5.     if(!isset($directory))  { return false; }
  6.     // if the path has a slash at the end we remove it here
  7.     if(substr($directory,-1) == '/') {
  8.         $directory = substr($directory,0,-1);
  9.     }
  10.     // if the path is not valid or is not a directory ...
  11.     if(!file_exists($directory) || !is_dir($directory))    {
  12.         // ... we return false and exit the function
  13.         return FALSE;
  14.     // ... if the path is not readable
  15.     } elseif(!is_readable($directory))    {
  16.         // ... we return false and exit the function
  17.         return FALSE;
  18.     // ... else if the path is readable
  19.     } else {
  20.         // we open the directory
  21.         $handle = opendir($directory);
  22.         // and scan through the items inside
  23.         while (($item = readdir($handle))!== FALSE ) {
  24.             // if the filepointer is not the current directory
  25.             // or the parent directory
  26.             if($item != '.' && $item != '..') {
  27.                 // we build the new path to access
  28.                 $path = $directory.'/'.$item;
  29.                 // if the new path is a directory
  30.                 if(is_dir($path)) {
  31.                     // we call this function with the new path, and the current counter
  32.                     preloadImages($path, $x);
  33.                 // if the new path is a file
  34.                 } else {
  35.                     // we get the file info
  36.                     list($width, $height, $type, $attr) = getimagesize($path);
  37.                     //and output the javascript code
  38.                     echo "pic".$x." =  new Image(".$width.",".$height.");\n";
  39.                     echo "pic".$x.".src=\"".$path."\";\n";
  40.             $x++;
  41.                 }
  42.             }
  43.         }
  44.         // close the directory
  45.         closedir($handle);
  46.  
  47.         // return success
  48.         return TRUE;
  49.     }
  50. }

To implement it, place it in the head section of your document like so:

HTML:
  1. <script language="JavaScript">
  2. <!--
  3. if (document.images)
  4. {
  5. <?php preloadImages("images") or die ("Unable to preload images"); ?>
  6.  
  7. }
  8. //-->
  9. </script>

images is the location of the images directory (in this case, its at the same level as the file that the javascript code is in). You may have to change this to match yours.

Note: This assumes that all files in the directory and sub-directories are images

Now lets go through the code and analyze whats happening.

Posted in Javascript, PHP.


3 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

  1. Wertverigat says

    Hi

    As a fresh http://www.ryanprice.ca user i only want to say hi to everyone else who uses this forum ;-)

  2. creativecomponent says

    Hey Ryan. This is EXCELLENT! Thanks so much.

    This runs perfectly in Firefox and Safari… However (there’s always a however), it doesn’t work at all in IE7/IE6.

    I tried a similar script to yours that didn’t look at the directory, but you would list all of the images in a row.

    I have over 400 images, so your script MUST work for me! :-)

    From what I can tell IE doesn’t like the Image() object.

    Is there a way around this? Thanks!

  3. Ryan Price says

    Hi Creative,

    Do you have a work-in-progress online I could look at? Hard to tell what the problem is without seeing it first.

You must be logged in to post a comment.