eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – Summer Sale 2026 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

Course – Summer Sale 2026 – NPI (cat=Baeldung)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

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.

Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – Summer Sale 2026 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

Course – Summer Sale 2026 – NPI (All)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

eBook Jackson – NPI EA – 3 (cat = Jackson)