lundi 23 mars 2020

Does putting

Every page regarding website optimizations clearly states that it's best to put <script> tags at the end of the <body>, instead of the <head> or at the start or middle of the <body>, and that's because loading scripts is parser blocking, as the DOM parsing is paused while the browser fetches the external script and then executes it, and only then can the DOM parsing resume. So putting the <script> tag just before the <body> closes means the DOM will finish parsing and the content will be rendered and then the script will run.

<html>
  <head>
    <script src="script.js"></script> <!-- bad -->
  </head>
  <body>
    <div>
      Hello World
    </div>
    <script src="script.js"></script> <!-- good-->
  </body>
</html>

While I get that, and I get that you can also use async and defer tags to continue parsing the DOM while fetching the scripts, there's one thing that doesn't make sense to me.

When not using async or defer but just placing the <script> just before the <body> closes, the DOM parsing is paused anyway, even if it just has to now parse the closing </body> tag. This means that if a script is loaded just before the <body> closes, the DOM parsing is halted until the script is loaded and run, and then the DOM parsing continues (for about 0.1ms because it only has to parse the closing </body> and </html>), and only then the first render happens.

Am I missing something here? Seems to me like putting the script at the end of the body doesn't actually speed up the initial render as the parsing is still blocked, even if 99.9% of the DOM has been parsed. Even the loaded script is slow then the initial render will be delayed anyway.




Aucun commentaire:

Enregistrer un commentaire