Let's get started with a Microservice Architecture with Spring Cloud:
Waiting for Complex Page With JavaScript to Load in Selenium WebDriver
Last updated: May 31, 2026
1. Introduction
When testing applications with Selenium, waiting for a page to load completely is more complex when it comes to modern pages, as they rely heavily on JavaScript for rendering. These kinds of pages make asynchronous calls and manipulate the DOM after the initial HTML has loaded. Therefore, checking if it’s loaded isn’t sufficient to ensure the app is ready for interaction.
Introducing an arbitrary delay is a common but problematic choice. If the page loads faster than the delay, the test wastes time. Otherwise, if the page loads slower due to network conditions or server response time, the test may fail.
In this tutorial, we’ll explore different strategies for waiting until a JavaScript-heavy page is fully loaded in Selenium WebDriver without introducing arbitrary delays.
2. Problem and Setup
We’ll define a page as loaded when all asynchronous operations for the current view have completed. This includes HTTP requests, dynamic DOM updates, and framework-specific processing. Navigating to a new view is treated as a new page load that requires its own wait strategy.
Selenium provides two main wait strategies. With implicit waits, we set a global timeout for element lookups. On the other hand, with explicit waits, we wait for specific conditions using a WebDriverWait instance. We’ll only use explicit waits, which provide precise control over what conditions to check.
2.1. Creating a Helper Class
Let’s create a helper class that encapsulates our waiting logic. It wraps a WebDriverWait instance and requires a timeout value so our tests don’t wait indefinitely in unexpected scenarios:
public class PageLoadHelper {
private final WebDriverWait wait;
public PageLoadHelper(WebDriver driver, Duration timeout) {
this.wait = new WebDriverWait(driver, timeout);
}
// ...
}
We’ll add all the different wait strategies to this class, making them easy to reuse. We’ll only need the until() method from WebDriverWait, which polls the condition until it returns true or times out. This condition is written as a lambda that takes the current driver:
public void waitUntil() {
wait.until(driver -> {
JavascriptExecutor js = (JavascriptExecutor) driver;
return // condition...
});
}
While we won’t need a specific driver implementation, the only requirement is that it implements the JavaScriptExecutor interface. We need this because the states we want to query are only accessible through the browser’s JavaScript runtime, not via the standard WebDriver API.
Also, since some of the checks rely on specific frameworks, most methods in this article start with checks such as typeof someFrameworkObject === ‘undefined’. If the framework isn’t there, the condition returns true immediately, making the method safe to call on any page and useful when chaining.
3. Waiting for Document Ready State
The most fundamental check is inspecting the browser’s document.readyState property. This property becomes complete when the page and all its resources have finished loading. It’s the default behavior of driver.get(). It’s useful for SPA navigation, such as right after clicking a link that changes the view without a full page reload.
Let’s add a method to our PageLoadHelper that executes a script and waits until it returns the result we’re looking for:
public void waitForDocumentReady() {
wait.until(driver -> {
JavascriptExecutor js = (JavascriptExecutor) driver;
return js.executeScript("return document.readyState")
.equals("complete");
});
}
While this covers the initial HTML page load, it doesn’t apply to asynchronous JavaScript that runs after the DOM is ready.
4. Waiting for jQuery AJAX Calls to Complete
Many apps still use jQuery for AJAX requests. It maintains an internal counter, jQuery.active, that tracks the number of pending requests. When this reaches zero, all requests have completed.
Let’s add a method that checks whether there are any pending requests:
public void waitForJQueryToFinish() {
wait.until(driver -> {
JavascriptExecutor js = (JavascriptExecutor) driver;
return (Boolean) js.executeScript(
"return (typeof jQuery === 'undefined') || (jQuery.active === 0)");
});
}
It first checks whether jQuery is present on the page. If not, the condition returns true immediately. This type of guard is useful when building a universal test suite, and not all pages use jQuery.
However, if an AJAX request hasn’t started yet when we call it, the condition sees jQuery.active === 0 and returns before any request fires. So, let’s create another method that waits for a request to start:
public void waitForJQueryToStart() {
wait.until(driver -> {
JavascriptExecutor js = (JavascriptExecutor) driver;
return (Boolean) js.executeScript(
"return (typeof jQuery === 'undefined') || (jQuery.active > 0)");
});
}
We can then chain these two to ensure that requests start before waiting for them to finish. But even with this approach, if all requests fire and complete before we have a chance to observe jQuery.active increasing, we’ll end up waiting until Selenium times out.
5. Waiting for Modern Angular Apps to Stabilize
Angular 2+ uses RxJS for HTTP calls, and it provides a testability API that allows us to check if the app is stable, meaning that it has completed all pending requests:
public Boolean waitForModernAngularAppStable() {
return wait.until(driver -> {
JavascriptExecutor js = (JavascriptExecutor) driver;
String script = """
return (
typeof getAllAngularTestabilities === 'undefined'
|| getAllAngularTestabilities().every(t => t.isStable())
)
""";
return (Boolean) js.executeScript(script);
});
}
We check whether getAllAngularTestabilities is undefined to guard against future API changes.
6. Waiting for React Apps to Be Ready
React apps don’t have a built-in JavaScript API we can use to test app readiness universally, so we have to handle it on a case-by-case basis. A common approach is to make an element visible only after we’ve finished making all the requests we need.
Something as simple as a “done” flag that adds a CSS class to a button is enough:
<button id="doneButton" className={done ? 'visible' : ''}>
All Done
</button>
Then, we can add an all-purpose method to wait for elements to be clicked:
public void waitForElementToBeClickable(By locator) {
wait.until(ExpectedConditions.elementToBeClickable(locator));
}
Finally, we can test it by passing the ID of the element:
@Test
void whenWaitForElementClickable_thenClickable() {
driver.get(PAGE_URL);
pageLoadHelper.waitForElementToBeClickable(By.id("doneButton"));
assertTrue(driver.findElement(By.id("doneButton")).isDisplayed());
}
This approach isn’t limited to React and can be used with any page. Most importantly, the done flag must be set when the application is truly ready for interaction. If completing the initial set of requests triggers additional requests, the flag must account for the entire chain before being set to true.
7. Injecting a Custom Flag in the Window Object
In modern JavaScript apps, we usually use Promises to make requests, and we can use the “Promise.all()” function to wait for a set of promises to complete. Most importantly, if we don’t have access to a universal tool, we can always modify the window variable to include our own flags.
So, if we know the slowest part of the app is completing a set of promises and we can’t reliably use the app before that, one alternative is creating a simple listener that adds a flag indicating when our app is ready:
window.appReady = false;
// start promises ...
Promise.all(promises).then(() => {
window.appReady = true;
});
It’s important to initialize the variable to false so we don’t get undefined when reading its value. We can then wait until this flag appears when testing the app with Selenium:
public void waitForJsAppReady() {
wait.until(driver -> {
JavascriptExecutor js = (JavascriptExecutor) driver;
return (Boolean) js.executeScript(
"""
return (
typeof window.appReady === 'undefined'
|| window.appReady === true
)
""");
});
}
This will work for any app running in a modern browser.
8. Patching the Fetch API
Another common approach in modern JavaScript apps is to use fetch, which also doesn’t provide a standard way to count pending requests. So, one option is to implement it on our own. We can do this by replacing the fetch implementation with a custom one that increments a global fetchPending counter and delegates the actual execution to the original implementation:
window.fetchPending = 0;
const originalFetch = window.fetch;
window.fetch = function(...args) {
window.fetchPending++;
return originalFetch.apply(this, args)
.finally(() => window.fetchPending--);
};
This must be called before the requests we want to track are fired. Then, every request made with the fetch command becomes trackable (even on error, since we decrement it in a finally block). Finally, we can wait until fetchPending reaches zero, like in our appReady solution.
For requests that fire automatically on page load, the interception must happen before navigation. Selenium now supports this via the Chrome DevTools Protocol, but that is beyond the scope of this article.
9. Summary
The strategies we covered address different scenarios. Let’s see how they compare:
| Approach | Best for | Limitation |
|---|---|---|
| document.readyState | All pages; SPA navigation | Already the default for driver.get(); doesn’t cover post-load async ops |
| jQuery.active counter | Pages using jQuery | Race condition if requests haven’t started; chain with waitForJQueryToStart() |
| Angular testability API | Angular 2+ apps | May not work with all Angular configurations |
| ExpectedConditions.elementToBeClickable | Any page with a sentinel element | Only checks the DOM state, not pending requests |
| Window flag (window.appReady) | Any app with code-level control | Requires modifying the application under test |
| Fetch API interception | Apps using the Fetch API | Must intercept before requests fire; auto-load requests require CDP |
In practice, combining strategies works best: start with waitForDocumentReady(), apply a framework-specific check, then confirm a meaningful element is interactable.
10. Conclusion
In this article, we explored several strategies for waiting until JavaScript-heavy pages fully load using Selenium. We started with the basic document.readyState check and covered Selenium’s built-in WebDriverWait for waiting on element states. We also extended our approach to handle jQuery AJAX calls, modern Angular applications, alternatives to React components, and pure JavaScript apps.
No single strategy covers all cases, and the right choice depends on the technologies the app uses and the level of control we have over its source code. Using a helper class like PageLoadHelper simplifies composing and reusing strategies across a test suite.
As always, the source code is available over on GitHub.

















