views:

622

answers:

1

Is there any way to find out that how many elements are going to be loaded in a webpage via javascript?
for example, I'm going to show the visitor something like this:

3 objects loaded, 10 ones remain! please wait.

+5  A: 

If by "elements" you mean DOM elements, no. You don't know they exist until they are loaded, and it's not very reliable to try to do DOM queries before it's finished loading anyway.

If you mean "images" or something along those lines, you could put something like this on your page:

<div id="loadingMessageContainer"></div>

And put this at the bottom of the page (below </body>)

<script type="text/javascript">
var imageCount = 0;
var imagesLoaded = 0;

//a function to execute when each image is loaded ("event handler")
function handleImageLoad() {
    imagesLoaded++;
    updateImageDisplay();
}

//a function which updates your message in the page
function updateImageDisplay() {
    var displayContainer = document.getElementById('loadingMessageContainer');
    var remaining = imageCount - imagesLoaded;
    displayContainer.innerHTML = imagesLoaded + ' objects loaded, ' + remaining + ' remain. Please wait.';
}

//get # of images on page and attach the OnLoad event handler
var images = document.getElementsByTagName('img');
imageCount = images.length;
for(var i=0;i<images.length;i++) {
    images[i].onload = handleImageLoad;
}
</script>
Rex M
thanks Rex, it's working nice ^-^
artarad