0

My javascript is running before my HTML loads, even if I put it right before the like this:

<body>
    <h1>Title</h1>
    <script>
        alert("yo");
    </script>
</body>

Any ideas why that may be happening?

  • Does this answer your question? [load and execute order of scripts](https://stackoverflow.com/questions/8996852/load-and-execute-order-of-scripts) – PeterS May 20 '21 at 13:52
  • yes, it's happening because Javascript is typically executed before anything else on the page, that's just the way it works. If you want to display the html first, you have to set a timer for like x seconds after, or do it on button click. I can help you if you need – Gianluca May 20 '21 at 13:52
  • 1
    Does this answer your question? [How to make the HTML renders before the alert is triggered?](https://stackoverflow.com/questions/40086680/how-to-make-the-html-renders-before-the-alert-is-triggered) – RCB May 20 '21 at 13:55
  • You should use `DOMContentLoaded` event to prevent that – Mir entafaz Ali May 20 '21 at 14:03

2 Answers2

1

Any ideas why that may be happening?

alert is blocking, script evaluation comes before DomContentLoaded (DCL) and subsequent first content paint (FCP) which is why it doesn't show Title before alert starts blocking the dom.

enter image description here

Lawrence Cherone
  • 46,049
  • 7
  • 62
  • 106
0

You could run it this way:

<body onload="alert('yo')">
    <h1>Title</h1>
</body>

Or this way:

<body onload="my_function()">
<h1>Title</h1>
<script>
    function my_function() {
        alert('yo');
    }
</script>
</body>
Wadih M.
  • 12,810
  • 7
  • 47
  • 57
  • 1
    Inline scripting isn't ideal. Also, this was obviously a duplicate. – isherwood May 20 '21 at 14:06
  • @isherwood I think inline scripting is fine if used properly. Causality is always clear. And I think above example illustrates some basic concepts in a simple way easy to understand. – Wadih M. May 20 '21 at 14:10