After that, loading the DOM is blocked by the script

Consider the following code:

<head> <style> .box{ background-color:red; height:150px; width:150px; } </style> </head> <body> <div class="box"></div> <script> var start = new Date(); while(true) { var now = new Date(); if (now-start > 10000) break; } console.log('main thread finished'); </script> </body> 

It is a big surprise for me that the DOM delays loading for ten seconds (a .box rectangle appears after 10 seconds! ). Since this is in the first place ( <div class="box"></div> ) , why does the script wait, what should I do? Any reasonable explanation?

thanks

+6
source share
5 answers

"Scripts without asynchronous or pending attributes, as well as embedded scripts, are retrieved and executed immediately before the browser continues to parse the page." - from MDN .

This way your script stops parsing for 10 seconds. Don't talk about page rendering. This was mainly done to support immediate html modifications from an executable script. For example, if your script calls document.write('More html') , this will affect parsing.

By the way, script execution has access to the DOM structure that has already been parsed . Consider the following example.

 <div class="box">Affected</div> <script> [].forEach.call(document.querySelectorAll('.box'), function(box){ box.innerText += '... modified'; }); </script> <div class="box">Not</div> 
+2
source

To simplify it, JavaScript is single-threaded, which means that it cannot take care of the DOM model while taking care of your little script. He goes one by one.

You can really find a full description here.

To avoid a problem with a blocked user interface, you may be interested in learning about Web Workers .

+1
source

Due to how the engine works (single thread), any script blocks any progressive rendering on the page below the script

enter image description here

+1
source

This script does not wait for the page to fully load before it starts. That is why you wait 10 seconds. That's why such code usually wraps window.onload or $ (document) .ready ().

0
source

According to the standard, the browser can display this element before the script is executed. But this does not mean that it is necessary. I checked your code in 4 browsers, and only one of them drew .box execution before the script - it was Opera 12. All other browsers - Chrome, FF, IE11 did not.

As I recall, chrome once said that it allows them to optimize something, and they thought that the speed of the Internet became big enough to wait for a full load.

0
source

All Articles