Answer
Handling Loader → Content Pattern in Selenium
This is a very common pattern: click action → spinner appears → content loads. You must wait for the spinner to disappear before interacting with the loaded content.
Standard Pattern
// Step 1: Click the action button
driver.findElement(By.id("loadDataBtn")).click();
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(20));
// Step 2: Wait for loader/spinner to DISAPPEAR
wait.until(
ExpectedConditions.invisibilityOfElementLocated(By.cssSelector(".spinner"))
);
// Step 3: Wait for content to APPEAR
WebElement content = wait.until(
ExpectedConditions.visibilityOfElementLocated(By.cssSelector(".data-container"))
);
// Step 4: Interact with loaded content
System.out.println("Content loaded: " + content.getText());
If Loader Is Not in DOM Initially
// Click
driver.findElement(By.id("loadBtn")).click();
// Wait for loader to APPEAR first (confirms action triggered)
wait.until(
ExpectedConditions.visibilityOfElementLocated(By.cssSelector(".loading-overlay"))
);
// Then wait for it to DISAPPEAR
wait.until(
ExpectedConditions.invisibilityOfElementLocated(By.cssSelector(".loading-overlay"))
);
// Now content is ready
Reusable Method
public void waitForLoaderAndContent(String loaderCss, String contentCss) {
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(30));
// Wait for loader to go away
wait.until(ExpectedConditions.invisibilityOfElementLocated(
By.cssSelector(loaderCss)
));
// Wait for content
wait.until(ExpectedConditions.visibilityOfElementLocated(
By.cssSelector(contentCss)
));
}
// Usage
clickLoadButton();
waitForLoaderAndContent(".spinner", ".results-grid");
Handle Slow Networks in CI
// Increase timeout for CI environments
int timeout = System.getenv("CI") != null ? 45 : 15;
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(timeout));
When Timeout Happens
If the wait times out, it is a real defect — the spinner never disappeared or content never loaded within the acceptable time. Log it, take a screenshot, and report it as a bug rather than increasing the timeout further.
