Reputation: 3370
Without inserting inline scripts, how can I check if a specific page has loaded? Usually I put an inline script that calls a function in the page's html head using window.onload, but how can this be achieved with a linked JavaScript file?
For example, suppose I have a button that opens a special page, and I need the DOM to be ready before I start any using scripts on that. Should I use two JavaScript files, linked at the bottom of each body?, then wrap everything in a function called by the onload event?
Upvotes: 0
Views: 425
Reputation: 14823
Let A be the page with the button you click.
Let B be the the special page that opens on A's button click
I struggle to understand what you're asking exactly, but this sounds like a case of "A comes before B".
If the button on page A is clickable after that page finishes loading, then the script that runs after page B finishes loading can safely assuming that both A and B have loaded. You can write logic in B that depends on A being loaded only if you can guarantee that A loads B. What happens if B is accessed directly bypassing A?
Possible markup for B follows:
<html>
<head>
<title>Special Page</title>
</head>
<body>
<script src="test.js"></script>
</body>
</html>
The test.js
file linked above:
window.onload = function(){
console.log('special page is loaded');
};
The onload event on page B may safely assume A has loaded but only if you can guarantee A always calls B.
I have no idea if you're trying to load page B into an iframe or do a page redirect from A to B or fetch B into A by way of Ajax and HTTP GET.
Upvotes: 1
Reputation: 133
It's pretty common practice to place the script tags at the bottom of the page, just before the final body tag. This will mean that the DOM would have loaded by this point and it will be safe to execute your code. Also it means that your scripts won't be downloaded till the very end which makes for a better experience for visitors.
If you wanted to be particular about it, you could then add an event listener onto the body tag and have your code run after body loads. I'm not sure your exact use case so I don't know if this would serve your purpose better. Assuming you aren't doing anything out of the ordinary and your scripts are placed just before the final body tag this wouldn't make much of an extra difference as the majority of the DOM would have already loaded. If you did want to do this you'd use the following code.
var bodyElement = document.getElementsByTagName("BODY")[0];
bodyElement.onload = function () {
// Your loading function
}
Upvotes: 1