Reputation: 139
i dont know why but my script is running before my html is completely loaded.
here is my html
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
hey
<script src="index.js" charset="utf-8"></script>
</body>
</html>
here is my script
document.addEventListener("DOMContentLoaded", function(){
alert("hi")
});
Upvotes: 1
Views: 589
Reputation: 73029
The DOMContentLoaded
event that you are listening to fires:
when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.
[MDN docs on DOMContentLoaded]
This may appear to happen before the page itself is painted to the screen.
If you want the alert to fire when the page has fully loaded, then you should listen to the window
's load
event.
window.addEventListener("load", function(){
alert("hi")
});
Let me know if that helps.
Upvotes: 1
Reputation: 153
<body onload="loadAlert()">
<script>
function loadAlert() {
alert("Hi!");
}
</script>
More from https://www.w3schools.com/tags/ev_onload.asp which has it all
Upvotes: 0
Reputation: 358
You can just put the JS at the end of your <body>
,(or right before the </html>
) it will execute when the page has loaded anyway. This is because the bits at the bottom are the last loaded in HTML.
Hope this helps.
Upvotes: 0