I understand that JS is single threaded and synchronously executed. Therefore when i add a file to my browser head tag that file is executed as soon as its encountered. Then it goes to the next script tag & executes that file. My question is when I add a js file dynamically to an HTML head tag. How does the browser executes that file?
Is it like that the file is executed as soon as the file is loaded wherever the current execution is. Or is it that we can control how that file is executed?
I understand that JS is single threaded and synchronously executed. Therefore when i add
Share
When the script is loaded, it will be executed as soon as possible. That is, if some other javascript function is executing, like a clickhandler or whatever, that will be allowed to finish first – but this is a given because, as you say, in browsers JavaScript normally execute in a single thread.
You can’t control that part of the script loading, but you could use this pattern – heavily inspired by JSONP:
inserted script:
script on main page:
The key here is the
readyfunction that is defined on your page, and called from the script you insert dynmaically. Instead of immediately starting to act, the script will only tell the parent page that it is loaded, and the parent page can then call back to the inserted scriptsinitfunction whenever it wants execution to start.