Reputation: 5893
Is Dynamic Script Tag Addition is Asynchronous? Like dynamically including set of JavaScript files from a different domain.
Upvotes: 5
Views: 2026
Reputation: 21840
Is Dynamic Script Tag Addition is Asynchronous?
Yes. It is considered asynchronous mostly because of what happens when the script tag is not dynamically inserted.
A fully formed script tag that exists in the DOM will cause blocking behavior, i.e. the page cannot continue loading other HTML until that particular asset is finished loading. Thus, many developers prefer to place their script tags just before the </body>
tag. In that way, a tag becomes referred to as synchronous
.
By contrast, if you dynamically inject a script tag, it tends to not exhibit blocking behavior. I say tends because as you've seen in other comments, not all browsers do that. The best thing is to wrap that dynamic script code in a document ready
callback of some kind. Thus, by contrast, it is technically asynchronous
because other assets can continue to function alongside that asset and its functionality.
Upvotes: 0
Reputation: 117028
Yes, it is asynchronous. Dynamic <script>
injection always results in the browser loading an external resource via the DOM (e.g. just like stylesheets, images, flash), which must happen asynchronously to avoid browser lockup.
Are you looking at JSONP ("JSON with Padding") by any chance? It uses dynamic script tag injection. It's more and more part of discussions about "AJAX", and the fact that it is impossible to do synchronous JSONP (like synchronous XmlHttpRequest
) is often overlooked.
Upvotes: 8