user3090914
user3090914

Reputation: 15

What happens when async=true is used inside document.ready?

What does happen when we call a javascript with attribute async="true" inside document.ready. For example,

$(document).ready(function() {
var ma = document.createElement('script');
ma.type = 'text/javascript'; 
ma.async = true;
ma.src = 'test.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ma,s);
});

Script inside $(document).ready will be executed immediately after the DOM is loaded. What does happen if we put async = truefor calling a script inside it? test.js will be loaded before DOM is ready?

Upvotes: 1

Views: 347

Answers (1)

user2864740
user2864740

Reputation: 61885

Scripts added via DOM manipulation are not synchronous wrt the JavaScript that adds them, independent of the async attribute.

The async attribute plays a larger role in scripts that exist in the initial HTML - before the "ready" - or when multiple script elements are added and the execution order must match the DOM insertion order:

Set this Boolean attribute to indicate that the browser should, if possible, execute the script asynchronously ..

.. script-inserted scripts execute asynchronously in IE and WebKit, but synchronously [wrt the insertion order of the script elements] in Opera and pre-4.0 Firefox. .. To request script-inserted external scripts be executed in the insertion order in browsers [..] set async=false on the scripts you want to maintain order ..

The browser will start loading the script referenced by the new script element "at some point after the element is added to the DOM" and the referenced script will only execute once loaded. However, insertBefore returns immediately and the referenced script is not guaranteed to be loaded - doesn't matter what async is set to.


In this case, the test.js code is guaranteed to only run "at some point after the script element is added" to the DOM - this must naturally be after ready function is called, which is where the element is added.

Since browsers have a single execution context, and adding the DOM element is an asynchronous operation (wrt the external script being executed), this also means that the code in test.js will only run "at some after the ready function ends". And, the ready function will not start (or end) before it is called in response to "DOM ready".

Setting the async flag (to any value) does not change the above.

Upvotes: 2

Related Questions