Monday, June 3, 2024
126
rated 0 times [  127] [ 1]  / answers: 1 / hits: 27175  / 14 Years ago, wed, august 4, 2010, 12:00:00

This question is sort of a tangent to Which browsers support <script async="async" />?.



I've seen a few scripts lately that do something like this:



var s = document.createElement('script');
s.type = 'text/javascript';
s.async = true;
s.src = 'http://www.example.com/script.js';
document.getElementsByTagName('head')[0].appendChild(s);


This is a common way to add a script to the DOM dynamically, which, IIRC from Steve Souders's book Even Faster Web Sites, prompts all modern browsers to load the script asynchronously (i.e., not blocking page rendering or downloading of subsequent assets).



If I'm correct in that, does the s.async = true statement have any use? Wouldn't it be redundant, even for the browser(s) that support that property, since dynamically appended a script should already trigger asynchronous downloading?


More From » asynchronous

 Answers
35

The specification (now) dictates that a script element that isn't parser-inserted is async; the async property is irrelevant to non-parser-inserted script elements:




The third is a flag indicating whether the element will force-async. Initially, script elements must have this flag set. It is unset by the HTML parser and the XML parser on script elements they insert. In addition, whenever a script element whose force-async flag is set has a async content attribute added, the element's force-async flag must be unset.




Having the async content attribute does, of course, mean the script would be executed asynchronously. The spec language seems to leave an opportunity to force synchronous execution of the script (by setting the attribute and then removing it), but in practice that does not work and is probably just a bit of vagueness in the spec. Non-parser-inserted script elements are async.



This specified behavior is what IE and Chrome have always done, Firefox has done for years, and current Opera also does (I have no idea when it changed from the old behavior in the answer linked above).



It's easily tested:



var script = document.createElement(script);
script.src = script.js;
console.log(a);
document.body.appendChild(script);
console.log(b);


...with script.js being



console.log(script loaded);


...will log




a
b
script loaded

[#96021] Monday, August 2, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tristani

Total Points: 318
Total Questions: 95
Total Answers: 106

Location: Saint Lucia
Member since Wed, Feb 8, 2023
1 Year ago
;