user441258
user441258

Reputation: 61

Dynamic addition of JS to head

When we dynamically insert JS spript in head, it triggers unblocking(or parallel with other resources) download of JS file. Once the JS gets downloaded, does the browser block while parsing and executing the script or the parsing and execution is also aynchronous?

var headID = document.getElementsByTagName("head")[0];         
var newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.src = 'http://www.somedomain.com/somescript.js';
headID.appendChild(newScript);

Upvotes: 1

Views: 544

Answers (2)

Rajat
Rajat

Reputation: 34118

Only the download happens in parallel. As mentioned by @BGerrissen, JavaScript is single threaded. Interpretation and execution will block the UI thread.

Upvotes: 1

BGerrissen
BGerrissen

Reputation: 21680

The following happens in order:

1.) script loads
2.) script gets interpretted (blocks javascript thread)
3.) script load/complete event fires.

JavaScript is single threaded, the interpretation and execution will therefor block other scripts. It will also block DOM rendering. The only advantage of adding scripts dynamically is to prevent the script load from blocking DOM rendering as well.

Upvotes: 2

Related Questions