Chris Chris - 2 months ago 9
Javascript Question

Will a script added with insertBefore (async=false) loaded next?

Let's asume I put this script directly after the starting head-tag:

(function () {
var a = document.createElement('script');
var m = document.getElementsByTagName('script')[0];
a.async = !1;
a.src = 'loader.js';
m.parentNode.insertBefore(a, m);
})();


Can I be sure, that the loader.js will be executed right after the above function block?

Although the loading of the loader.js is inserted before the current position the browser is executing.

Answer

According to MDN:

Script-inserted scripts execute asynchronously in IE and WebKit, but synchronously in Opera and pre-4.0 Firefox. In Firefox 4.0, the async DOM property defaults to true for script-created scripts, so the default behavior matches the behavior of IE and WebKit. To request script-inserted external scripts be executed in the insertion order in browsers where the document.createElement("script").async evaluates to true (such as Firefox 4.0), set .async=false on the scripts you want to maintain order.

Comments