How to Get Your Web Page to Preload Before Displaying
As technology evolves and Web pages display faster, Internet users become accustomed to seeing events happen when they request them. For instance, if site visitors click a button named "View Image," they expect the image to appear instantly when clicked. One way to insure that this happens is to preload large Web page images. Preloading insures that all objects on a page are ready to use when a user needs to access them. Preload your Web page's images by adding a few lines of JavaScript to your HTML code.
Instructions
-
-
1
Open an HTML page using Notepad or an HTML editor.
-
2
Paste the code shown below into the document's body section:
<img src="firstImage.jpg" />
<img src="secondImage.jpg" />
<img src="thirdImage.jpg" />This code creates three images. Replace the three image names - firstImage.jpg, secondImage.jpg and thirdImage.jpg - with the names of images on your hard drive or the URLs of images on the Web.
-
-
3
Locate the document's script section and paste the following JavaScript code into that section:
var preLoadedObjects = [
"firstImage.jpg",
"secondImage.jpg",
"thirdImage.jpg"
];This code creates an object named "preLoadedObjects." This object holds the names of all images you wish to preload. Replace the three names shown above with the three file names you used in the body section.
-
4
Paste the following code below the code shown in the previous section:
for (var i = 0; i <= preLoadedObjects.length; i++) {
var currentImage = new Image();
currentImage.src = preLoadedObjects[i];
}This code runs when your Web page loads. It loops through each item in the preLoadedObjects object, creates an image and sets the image's "src" attribute to the image's location.
-
5
Save your document and view it in a browser. The JavaScript code runs and preloads the images. After the images load, the Web page appears.
-
1
Tips & Warnings
The preLoadedObjects object shown in this example contains three image names. Add additional images to this object as needed by simply adding new names to the list. Separate each name with a comma. Do not place a comma after the final name.
If you have large images and wish to preload them, consider displaying a "Loading" message on your page or showing site visitors some helpful or entertaining information. This will keep them from having to view a blank page while your images load.
References
Resources
- Photo Credit Comstock Images/Comstock/Getty Images