1

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")
    });
anonymous_coder
  • 119
  • 1
  • 9

3 Answers3

1

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.

philnash
  • 70,667
  • 10
  • 60
  • 88
  • There doesn't look to be a lot of content on the page in your example. Can you describe a bit more about what you are experiencing? What is happening and what do you expect to happen? – philnash May 12 '20 at 06:24
  • thanks for the code. i got it solved, window.addEventListener("DOMContentLoaded", function(){ alert("hi") }); – anonymous_coder May 12 '20 at 06:34
0

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.

CPlusPatch
  • 318
  • 2
  • 11
  • I think, as RingGamesCompany said, this might be normal with alert() anyway. I don't know why, but I've witnessed it. Maybe try jQuery's $(document).ready(). – CPlusPatch May 12 '20 at 05:45
  • i am new to all this concepts, i dont know how to use jQuery. is there anyway i can do it in js? – anonymous_coder May 12 '20 at 05:48
  • Yes, all you have to do is put the code at the end of the body, just before the `` tag. The cool thing about this is that it doesn't what for the images to load, just the JS stuff. It's the same as the other posts but I find it quicker. Sorry again about the wrong answer. Hope it helps! – CPlusPatch May 14 '20 at 12:03
0
<body onload="loadAlert()">

<script>
function loadAlert() {
    alert("Hi!");
}
</script>

More from https://www.w3schools.com/tags/ev_onload.asp which has it all