There is the onload event and there is the concept of a page fully loaded. I believe Selenium will wait for the onload event. Once the onload event is fired, the Ajax and Javascript starts running. This code could then load more things into the DOM. For example a page might be 200 bytes and only be an empty <body> and lots of Javascript. The moment the 200 bytes are loaded an onload event will fire. The Javascript might then start loading megabytes of other data and populate the DOM with <DIV>, <SPAN>, <TABLE>, etc.
So the question is, do you want to wait for the onload event to be fired? Or do you want to wait for all network activity and Javascript activity to finish? The onload event should be easy. It will just happen without you doing anything special. If you want to wait for all the elements to be loaded (via Ajax) and the DOM to be built (via Javascript) then it becomes a lot harder.
On some projects I have had the developers expose Ajax code which tells me when it is done. I can then use a JavascriptExecutor to check if the page is fully loaded. The developers would increment a counter for each Ajax call. When the Ajax call returned they would decrement the counter. When the counter when to zero it meant that all the Ajax calls had returned and the page was fully loaded. I needed the developers to do something for this to work.
Some Javascript libraries will give you a counter for free. If the team is always using the library call, you can leverage the counter which comes with the library.
The other option is to just look for specific WebElement to load. When they have all loaded you can count the page as fully loaded. Or you could try:
driver.findElements(By.xpath("//*"));
to get all the elements loaded. You could loop until the .size() of the List reaches the expected amount (not a good idea) or you could get the List, save current size, wait 1 second, get the List and see if it current size > previous size. If the size is still growing, keep looping. If not, assume the page is loaded and finish the method, e.g.
public boolean waitForPageFullyLoaded(WebDriver driver, int timeoutMs) {
int previous;
int current = 0;
int timeSliceMs = 1000;
do {
previous = current;
Thread.sleep(timeSliceMs);
timeoutMs -= timeSliceMs;
current = driver.findElements(By.xpath("//*")).size();
} while(current > previous && timeoutMs > 0);
if(timeoutMs > 0) {
return true;
}
return false;
}
Darrell