javascriptimagewebgalleryphotos

Preloading images in Javascript


I have created a simple photo gallery viewer, and I would like to preload the images in the background, and then run a function when they are done.

My question is, how do I do that?


Solution

  • var image = new Image();
    image.src = "http://foo.com/myimage.jpg";
    
    //if you have a div on the page that's waiting for this image...
    var div = getElementById("imageWrapperDiv");
    
    //you can set it on the image object as the item to draw into...
    image.myDiv = div;
    
    image.onload = function(){
      //do whatever you're going to do to display the image
    
      //so in this example, because I have set this objects myDiv property to a div on the page
     // I can then just populate that div with an img tag.
     //it's not the most elegant solution, but you get the idea and can improve upon it easily
      this.myDiv.innerHTML = "<img src='" +  this.src  +"'>";
    }
    

    Once the image loads, it's in the browser's cache, so, if you use the src property you can draw it anywhere on the page and it will display instantly.