-3
<body>
    <p>How many times could you do this?</p>
    <script>
        alert('Hello World'); 
    </script>
</body>

I'd appreciate your kind explanation as to why the alert pups up first, while the content of <p> only appears after clicking ok on the alert message.

charlietfl
  • 170,828
  • 13
  • 121
  • 150
J. Silver
  • 1
  • 1
  • 5
  • 1
    Nothing in what is shown would prevent the `

    ` being displayed immediately. Perhaps in css or script not shown but for that we have no way to even guess. Please provide a [mcve]

    – charlietfl Jul 09 '17 at 23:50
  • Thanks. It's a simple html. Only doctype and head tag is not included for space saving. No css used. – J. Silver Jul 09 '17 at 23:54
  • I've just noted that the above happens on Chrome, but the

    content is shown on Firefox. Any idea why Chrome is behaving this way.

    – J. Silver Jul 10 '17 at 00:15

2 Answers2

1

This is not true in general. I assume you tried this in Chrome. Have you tried using Firefox? IE? before posting this?

In FF browser it still render the DOM and download the script in the background, thus it still show the content in the background. I tried it in IE10 as well, and it do the same with FF. But the bottom line is some browser executes and downloads JS when it encounters a <script> tag in the structure.

To prevent executing script before the DOM is render you should wrap your script with something like:

$(document).ready(function(){
    alert('Hello World');   
});

You can read also here

But I'm not really sure what is the point of your question.

threeFatCat
  • 840
  • 13
  • 30
  • Thanks to all. Now I have a better understanding of how browsers treat js scripts. – J. Silver Jul 10 '17 at 01:52
  • This "something" requires the bloat of JQuery, though – OneCricketeer Jul 12 '17 at 12:24
  • Well if you want to have an equivalent of `document.ready` in pure javascript. You can check it [here](https://stackoverflow.com/questions/9899372/pure-javascript-equivalent-to-jquerys-ready-how-to-call-a-function-when-the). :) – threeFatCat Jul 12 '17 at 23:58
0

Scripts without async or defer attributes are fetched and executed immediately before the browser continues to parse the page

defer is set to indicate to a browser that the script is meant to be executed after the document has been parsed.

Hope this helps you

Vash
  • 141
  • 11