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

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

This question is sort of a tangent to Which browsers support

4条回答
  •  北荒
    北荒 (楼主)
    2020-11-29 02:44

    Interesting - I think it turns out that I was wrong in my assumptions.

    Based on this thread in the jQuery developers' forum:

    http://forum.jquery.com/topic/jquery-ajax-async-vs-html5-script-async

    it looks like the async property has been discovered to have an effect on dynamically-appended scripts, at least in Firefox (and potentially Opera, though it doesn't yet support the property).

    The forum thread also cites Google's asynchronous tracking code implementation, which, although it appears to make use of the async property in the appropriate context, actually appears to get the syntax wrong. Google uses:

    ga.async = true;
    

    when apparently that doesn't work; the proper method would be to use either:

    ga.async = 'async';
    

    or

    ga.setAttribute('async', 'async');
    

    So, based on my current understanding, not all browsers will actually execute dynamically-appended scripts immediately upon their insertion into the DOM in all cases; Firefox (and eventually Opera) will need the async property to be set to ensure that this always happens.

    More info on Firefox's implementation of async here:

    https://bugzilla.mozilla.org/show_bug.cgi?id=503481

提交回复
热议问题