Script Tag - async & defer

前端 未结 8 1671
隐瞒了意图╮
隐瞒了意图╮ 2020-11-22 13:52

I have a couple of questions about the attributes async & defer for the

8条回答
  •  Happy的楠姐
    2020-11-22 14:22

    It seems the behavior of defer and async is browser dependent, at least on the execution phase. NOTE, defer only applies to external scripts. I'm assuming async follows same pattern.

    In IE 11 and below, the order seems to be like this:

    • async (could partially execute while page loading)
    • none (could execute while page loading)
    • defer (executes after page loaded, all defer in order of placement in file)

    In Edge, Webkit, etc, the async attribute seems to be either ignored or placed at the end:

    • data-pagespeed-no-defer (executes before any other scripts, while page is loading)
    • none (could execute while page is loading)
    • defer (waits until DOM loaded, all defer in order of placement in file)
    • async (seems to wait until DOM loaded)

    In newer browsers, the data-pagespeed-no-defer attribute runs before any other external scripts. This is for scripts that don't depend on the DOM.

    NOTE: Use defer when you need an explicit order of execution of your external scripts. This tells the browser to execute all deferred scripts in order of placement in the file.

    ASIDE: The size of the external javascripts did matter when loading...but had no effect on the order of execution.

    If you're worried about the performance of your scripts, you may want to consider minification or simply loading them dynamically with an XMLHttpRequest.

提交回复
热议问题