Is the “async” attribute/property useful if a script is dynamically added to the DOM?

前端 未结 4 1836
栀梦
栀梦 2020-11-29 02:05

This question is sort of a tangent to Which browsers support

4条回答
  •  -上瘾入骨i
    2020-11-29 02:45

    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
    

提交回复
热议问题