I'm facing a challenge in executing a JavaScript function after the script has been loaded on an HTML page. The issue arises because the JavaScript script takes some time to load on the HTML page. It functions properly only if I introduce a delay of a few seconds in my Java code before executing the JavaScript function.
index.html
<!DOCTYPE HTML>
<html lang="en">
<head>
</head>
<body>
</body>
<script>
var loadJS = function(url) {
var script = document.createElement("script");
script.src = url;
document.body.appendChild(script);
}
</script>
</html>
Java Code
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("www.test-url.com");
js.executeScript("loadData(123)");
The provided code successfully executes when Thread.sleep(5000);
is included between the lines with the js.executeScript commands, but fails when this delay is omitted. How can I eliminate the need for Thread.sleep(5000);
and still achieve the desired functionality?