Why JavaScript is executed first, and only then displays the HTML?

Started to learn JS. I always thought that the browser handles the HTML code sequentially displays all the elements, and the script executes only when it comes to business, but now after trying to protest this case it turns out that in Chrome (other browsers not tested) everything is different: first the script and then displays the HTML elements... why? As it should be? Here is the code just in case:



 <meta charset="UTF-8">
 <title>JavaScript Tutorial</title>


 <h1>I'll Take You To The Candy Shop...</h1>
the <script>
 alert("I'll let you lick a lollipop...");
</script>
 <h2>Go ahead girl, don't you stop...</h2>

June 26th 19 at 13:59
2 answers
June 26th 19 at 14:01
Solution
Well, that chrome, apparently, decided to take "optimizations" and again to go against the grain, that is standards.

Don't be surprised the chrome is not the first time.
Thanks for the reply, in all the latest Firefox really does work, apparently chrome dabbles... - lewis_McLaughlin59 commented on June 26th 19 at 14:04
I'm personally in the Edge I checked, it is safer now. - Haylie_Oberbrunner commented on June 26th 19 at 14:07
June 26th 19 at 14:03
First parsed the html page. During this process, if the tag parsing pages of continues. If you want to run some js after it's loaded(for example you have to interact with html elements), then this code is added in the callback event ready.

the <script>
window.onload = function() { 
 alert( 'DOM loaded' );
};
</script>


More details can be read here
made it clear that this is a bug of chrome itself. Check out the snippet in fiddle. - lewis_McLaughlin59 commented on June 26th 19 at 14:06
Thank you for your answer, but I'm not very well versed in this subject and actually, as I wrote, just started learning JS, so the meaning of your answer it came to me with a 99% loss. Could you explain it in plain language, for such teapot as I am? - Haylie_Oberbrunner commented on June 26th 19 at 14:09
Well, if more than just malcahy
you have a browser that tries to display your page. He goes and turns processes your tags, and here he encounters a script tag. at this point, the html parsing is suspended and the processing js.
In your case, the system displayed the message window alert. Is this behavior.
Maybe there is a situation that you in your js you need to refer to html and to do that either. In this case, such code should be placed in a code block which is executed only at the moment when all the html is rendered and pohruzytsya all resources. In your case it would look like this:



 <meta charset="UTF-8">
 <title>JavaScript Tutorial</title>


<h1>I'll Take You To The Candy Shop...</h1>
the <script>
 window.onload = function() {
 alert( 'the HTML and all resources loaded' );
};
</script>
<h2>Go ahead girl, don't you stop...</h2>

- Haylie_Oberbrunner commented on June 26th 19 at 14:12

Find more questions by tags JavaScript