Wait for complex page with JavaScript to load using Selenium.

We can wait for a complex page with JavaScript to load with Selenium. After the page is loaded, we can invoke the Javascript method document.readyState and wait till complete is returned.


JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("return document.readyState").toString().equals("complete");

Next, we can verify if the page is ready for any action, by using the explicit wait concept in synchronization. We can wait for the expected condition presenceOfElementLocated for the element. We shall implement the entire verification within the try catch block.


import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.JavascriptExecutor;
public class PageLoadWt{
   public static void main(String[] args) {
      WebDriver driver = new ChromeDriver();
      // Javascript Executor to check page ready state
      JavascriptExecutor j = (JavascriptExecutor)driver;
      if (j.executeScript
      ("return document.readyState").toString().equals("complete")){
         System.out.println("Page loaded properly.");
      //expected condition presenceOfElementLocated
      WebDriverWait wt = new WebDriverWait(driver,3);
      try {
         // identify element
      catch(Exception e) {
         System.out.println("Element not located");