How to control the load order of images
(The contents of this article have been tested with Internet Explorer 5.5 (and above) and with Netscape 6.2 and later including Mozilla and Firefox.)
When an image is inserted as part of an html file the author has no (easy) control over the order in which the image is loaded. Normally the browser will start to load each image as soon as it encounters it in the html file, and there is no control over the order in which multiple images are loaded.
The script used here is slightly different from the one above - the 'Start' button sets the script going and the 'Reset' button clears the images down to allow it to be run again - but otherwise it is the same. As in the script shown above, the images initially are left blank.
How does this script work?
- Firstly, no images are loaded until the end of the document is reached. This allows any and all of the text content of the document to load before any images. All the images are defined without an image source (src) being defined for them (this is important - see point 4).
- Each image has a unique name, this allows the image to be referenced in the code.
- At the end of the file a call to the function 'LoadImage' (which takes the name of the image and the name of the file to load) and this starts the process of image loading.
- The images in this example are loaded sequentially (it is the successful
loading of each image which is used as the trigger to load the next). So
the second image is only loaded once the first image has finished
loading and so on. This is accomplished by having an '
onLoad' event handler associated with each image. The
onLoadevent handler is called by the browser when the image finishes loading (and this is why the initial images are defined without an image source.)
Alternately, if you simply want to delay loading images until after the text content of a file has been loaded but are not concerned about the order in which those images are loaded then the above can be simplified down to:
This script simply kicks off the loading of each image in turn. It is
important that the script (specifically the calls to '
is at the end of the file, i.e. after any text content.
To get a true impression of the speed difference between the two scripts it may be desirable to clear your browser cache before clicking the 'Start' button. Otherwise images will be retrieved from your browser's cache and this will be considerably faster than loading them from across the net.