0

Possible Duplicate:
JavaScript Preloading Images

I am using JS to set img.hidden=false some time after the page has loaded. This causes the image to download and resizes the img element - which I would like to avoid (I am using inline style width:2em to size the image). Secondly when I change the img source, there is a slight delay as the second image downloads.

How can I download my images prior to showing them on the page...?

Community
  • 1
  • 1
icekreaman
  • 363
  • 2
  • 9

2 Answers2

2

First download the image and then trigger the action, in this way with jquery:

  var i = document.createElement('img'); // or new Image()
  // may be you need to set the element id...
  i.id = 'your id';
  // here handle on load event
  $(i).load(function() {

       // finally the new image is loaded, you can trigger your action
       $('#container').append($(this));

  });
  // This is the last step, set the url and start the image download.
  i.src = 'http://www.hostname.com/yourimage.jpg';
freedev
  • 25,946
  • 8
  • 108
  • 125
1

Without jQuery (if needed):

var imageNode = new Image(); // or document.createElement('img');

imageNode.onload = function(e) {
    // Code for appending to the DOM
    document.getElementById('container').appendChild(this);
};

imageNode.src = 'path/to/image.jpg';

If your img tag does already exist like this:

<img id='myimg' alt=''>

In JavaScript use:

var imageNode = document.getElementById('myimg');

Instead of:

var imageNode = new Image();

Keep in mind that the code needs to be executed after the img tag or when the DOM is ready/loaded. Otherwise it does not exist when the code is executing

freakerd
  • 91
  • 3