frequently ask ? : Computers : Programming : Languages : JavaScript : Images

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

4 of 5 people (80%) answered Yes
Recently 1 of 2 people (50%) answered Yes

Entry

How can I cascade the loading of images, so that the second loads after the first, the third after the second and so on?

Mar 22nd, 2001 05:18
Martin Honnen,


The following code works with NN4 and IE4+ but has one main 
disadvantage: NN4 requires you to provide a SRC attribute for an IMG to 
lay it out and you can't change the size of the IMG later. So all images 
get written out with some fixed height and width. With this restrictions 
the loading of images on the page is cascaded.
<HTML>
<HEAD>
<SCRIPT>
var images = new Array('kiboInside.gif', 'buttonOn.gif', 
'buttonOff.gif');
var nonExistantImage = 'dummy.gif';
var width = 100;
var height = 200;
var i = 0;
function writeImage() {
  if (i < images.length) {
    var html = '';
    html += '<img name="image' + i + '"';
    html += '  src="' + nonExistantImage + '"';
    html += '  width="' + width + '" height="' + height + '"';
    i++;
    if (i < images.length)
      html += '  onload="document.images[' + i + '].src = 
window.images[' + i + '];"';
    html += '>';
    document.write(html);
  }
}
</SCRIPT>
</HEAD>
<BODY ONLOAD="document.images[0].src = images[0];">
<SCRIPT>
writeImage();
</SCRIPT>
<BR>
<SCRIPT>
writeImage();
</SCRIPT>
<BR>
<SCRIPT>
writeImage();
</SCRIPT>
<BR>
</BODY>
</HTML>