How do you know if everyone is loaded on the page?

I am creating a page with lots of ajax calls and dynamically creating the DOM. What is the best way to know if the entire ajax call has been made and all DOM elements are complete ?! I tried following the prototype.js event watcher:

Event.observe(window, 'load', function () {
 alert("Loaded!");
}); 

      

But it looks like after the warning was issued some items are still loading. I am trying to do this in IE.

+3


source to share


3 answers


You need to respond to the completion of ajax calls by adding code to your handlers success

(or complete

).

For example, suppose you are making three ajax calls to populate the DOM. After each ajax call, increment some global counter by 1, then call a function that checks if the counter is three (which means all ajax calls are complete). If so, you run yours alert('Loaded!');

.



It's easier to do this with objects $.Deferred()

if you are using jQuery for your ajax calls.

0


source


If you have a lot of ajax calls returning elements on your page, then the only way to know when they are all finished is to track them and use your development callbacks when everything is loaded. Load or ready events on the page are only related to resources loaded via html and not loaded via asynchronous requests. Asynchronous

is the key bit here.

If I were you I would have two global variables: totalNumberOfCalls

andfinishedCalls

At the beginning of my page, I would set totalNumberOfCalls to the correct number, and then for each callback, I would have a little bit of code like this:

if (++finishedCalls == totalNumberOfCalls) console.log('Page Loaded');
else console.log( (finishedCalls / totalNumberOfCalls) * 100 + '% loaded');

      



This way you can easily add a simple counter to track your progress.

If you're loading images and other external elements, it might be worth doing a count of the events of the load

returned elements so that you get the actual end time of the load, not the time the request returned, but not the associated resources.

If this all seems too big, then just make ajax calls synchronous

, this way the page will be stopped during calls. However, this is not a good practice.

0


source


You need to look at Ajax.Responders

http://api.prototypejs.org/ajax/Ajax/Responders/

This will register a global event callback for the given event

It Ajax.activeRequestCount

will also tell you how many active calls are running

var callback = {
  onComplete: function() {
    if(Ajax.activeRequestCount === 0){
        //all ajax calls are finished

        //If you only want to run this once make sure you unregister the event handlers
        Ajax.Responders.unregister(callback);
    }
  }
};
Ajax.Responders.register(callback);

      

0


source







All Articles