Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in DevOps and Agile by (19.7k points)

Is there a universal approach for Selenium to wait till all ajax content has loaded? (not tied to a specific website - so it works for every ajax website)

1 Answer

0 votes
by (62.9k points)
edited by

You are required to wait for Javascript and jQuery to finish loading. Execute Javascript to check if jQuery.active is 0 and document.readyState is complete, which will mean the JS and jQuery load is complete.

public boolean waitForJSandJQueryToLoad() {

 

    WebDriverWait wait = new WebDriverWait(driver, 30);

 

    // wait for jQuery to load

    ExpectedCondition<Boolean> jQueryLoad = new ExpectedCondition<Boolean>() {

      @Override

      public Boolean apply(WebDriver driver) {

        try {

          return ((Long)((JavascriptExecutor)getDriver()).executeScript("return jQuery.active") == 0);

        }

        catch (Exception e) {

          // no jQuery present

          return true;

        }

      }

    };

 

    // wait for Javascript to load

    ExpectedCondition<Boolean> jsLoad = new ExpectedCondition<Boolean>() {

      @Override

      public Boolean apply(WebDriver driver) {

        return ((JavascriptExecutor)getDriver()).executeScript("return document.readyState")

        .toString().equals("complete");

      }

    };

 

  return wait.until(jQueryLoad) && wait.until(jsLoad);

}

If you are interested to learn Selenium on a much deeper level and want to become a professional in the testing domain, check out Intellipaat’s Selenium automation online training

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...