Search code examples
javascripthtmlcssimagepreload

JavaScript Pre-loading Randomly Named Images from Site Directory


I have an HTML website with videos and custom video control buttons. When you hover over the play/pause button for example, it uses CSS to change to a different photo of the play button with a different colour but if you are going over it for the first time since loading or reloading the page, it goes blank when you hover on it because it has to load the image that it changes to on hover. I found a way to pre-load images that have numeric names starting from one. I have a set of thumbnail images and they all have a number + 'mo.png' as a name. It goes 1mo.png, 2mo.png and so on. I used this method to pre-load them all automatically:

for(var x = 1; x < 5; x++){
    no = x.toString();
    cs = 'img' + no + ' = new Image(); img' + no + ".src = 'media/" + no + "mo.png';";
    eval(cs);
}

But that only works for images that go from 1mo.png to 4mo.png (the 4 can be changed based on how many pictures with 'mo' at the end of their name I want to pre-load).

I want JavaScript to go through the images folder in my directory and using the same method I used for the 'mo' images pre-load any images it finds with any random name. Pretty much all I need to know is how to get file names from a certain folder in my site's own directory and store them in an array or variables.


Solution

  • Client-side Javascript in the browser won't have direct access to your server's directories. Any server-side language like Node, Ruby, Python, and PHP can parse your files and directories.

    I'd set up a script in the language of your choice that returns folder contents as jsonp so you can call it from other domains without a cross site scripting error. Then request that folder contents script via ajax in Javascript.

    SO question on the same topic:

    list all images in directory in JSON

    Here's another PHP function that would help.

    print_r(scandir('/var/www/yoursite.com/media'));
    

    http://www.php.net/manual/en/function.scandir.php