Do browsers execute loaded scripts in a single thread?

I can write the following:

<script src="file1.js" defer></script> <script src="file2.js" defer></script> <script src="file3.js" defer></script> 

This means that files can be downloaded in parallel, but only executed one after the other. However, I can add the async attribute so that the browser executes the code in random order.

 <script src="file1.js" async></script> <script src="file2.js" async></script> <script src="file3.js" async></script> 

If I'm interested in improving performance, can the second block run faster? As I can see, if the browser runs all JavaScript in one thread, then the total execution time for 3 scripts is no different from the first block, only the execution order may differ. I'm right?

+5
source share
1 answer

If I'm interested in improving performance, can the second block run faster?

Since scripts will load and execute asynchronously, yes, this will reduce page load time.

The author of Script-injection "asynchronous scripts that are considered malicious , compares three methods for including a script: the entered script, which blocks the script and the script with the async attribute. Result:

  script execution onload ----------------- ------------------ -------- script-injected ~3.7s ~3.7s blocking script ~2.7s ~2.7s async attribute ~1.7s ~2.7s 

As you can see, the async attribute gives better performance. If the execution order of the scripts does not matter, you should definitely use it.


Regarding your title question:

Do browsers execute loaded scripts in a single thread?

Yes, since JavaScript is single-threaded, but it does not matter in terms of performance. Downloading a script takes much longer than executing it, so you should focus on optimizing the portion of the download.


I did a test. I created a simple script:

 for (var i = 0; i < 1e8; i++); 

I put the same script in two files, test1.js and test2.js . Then I made two HTML files, the first without async , and the second with:

test1.html :

 <!DOCTYPE html> <script src="test1.js"></script> <script src="test2.js"></script> 

test2.html :

 <!DOCTYPE html> <script src="test1.js" async></script> <script src="test2.js" async></script> 

Then I opened these HTML files in my browser and checked the Timeline tab in Chrome DevTools:

test1.html :

test2.html :

As you can see, in both cases the scripts are not executed asynchronously.

See also: Is JavaScript guaranteed single-threaded? .

+6
source

Source: https://habr.com/ru/post/1246916/


All Articles