Selenium Automation : Waiting for a Page load and Ajax response

Waiting for a Page load or an ajax call is one of the important functions that an Automation Framework has to provide. There are multiple ways of waiting for a page load but not all of them are recommended.

Thread.Sleep(time in milliseconds) is probably the easiest and one of the worst ways to wait in a selenium or Non selenium based Automation framework because you are explicitly asking the driver to wait for, lets say 5 seconds, every time a function is called. Each page might have a different Page load time and your solution will have to be implemented in every page separately with a different time duration

Selenium provides you with Explicit and implicit Wait functions as well but again the logic is not dynamic enough to handle every page. Each page might have a different number of Ajax calls. Drivers implicit wait time will lead to the same problem that thread.sleep leads you to. Explicit wait is basically waiting till a condition is met for example an element being visible or element being present. So Explicit wait time will have to be used for each page separately.

The most efficient way to wait for an ajax response or a page load would be one that can be used for any of the Pages without modifying it.

IJavaScriptExecutor is  a powerful tool that selenium provides and it can do wonders, if one is strong in javascript and jQuery. Below is a function ( C#)  that waits for all the ajax calls to complete and  can be called for any of the pages that fires jquery ajax calls. The Timeout is basically optional, to make sure the function automatically finishes in 60 seconds and does not run for ever.

public void WaitForAjaxToComplete(int timeoutInSeconds = 60)
var endTime = DateTime.Now.AddSeconds(timeoutInSeconds);
while (DateTime.Now < endTime)

var isAjaxComplete =
(bool)((IJavaScriptExecutor)Driver).ExecuteScript(“return == 0”);

if (isAjaxComplete)



Additionally, for pages with spinner, we can have an additional flag, that checks for the spinner to complete and finish because browser rendering can take a couple of extra seconds.