DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Check If All The Images Have Been Loaded

02.21.2006
| 2287 views |
  • submit to reddit
        Javascript
function allImagesLoaded
This checks if all the images have been loaded on the page
Returns 1 if all are loaded and 0 if they are not
The great thing is that it works on images that you dynamicaly add with javascript (common for ads, tracking and other 3 party solutions)


	// allImagesLoaded()
	// Checks if all the images are loaded in the document
	// It Does this by looping through all the images and checks the attribute .complete
	// If .complete is false then we set the return variable to 0
	function allImagesLoaded() {
	
		// return variable
		var imagesloaded = 1;
	
		// All images are saved in an array called document.images. Very usefull
		var images = document.images;
		// Loop through all the images
		for (var i = 0;i<images.length;i++)
		{
			// If the image isnt loaded we set the return varible to 0
			if(images[i].complete == false) {
				imagesloaded = 0;
			}
		}
	
		// This will return 0 if one or more images are not loaded and 1 if all images are loaded.
		return imagesloaded;
	}

    

Comments

Snippets Manager replied on Mon, 2006/07/17 - 2:42pm

if(images[i].complete == false) { imagesloaded = 0; //should probably add a break statement here //no point in continueing if an image isn't loaded break; }