Script Tag - async & defer

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

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

相关标签:
8条回答
  • 2020-11-22 14:20

    Faced same kind of problem and now clearly understood how both will works.Hope this reference link will be helpful...

    Async

    When you add the async attribute to your script tag, the fol­low­ing will happen.

    <script src="myfile1.js" async></script>
    <script src="myfile2.js" async></script>
    
    1. Make par­al­lel requests to fetch the files.
    2. Con­tinue pars­ing the doc­u­ment as if it was never interrupted.
    3. Exe­cute the indi­vid­ual scripts the moment the files are downloaded.

    Defer

    Defer is very sim­i­lar to async with one major dif­fer­er­ence. Here’s what hap­pens when a browser encoun­ters a script with the defer attribute.

    <script src="myfile1.js" defer></script>
    <script src="myfile2.js" defer></script>
    
    1. Make par­al­lel requests to fetch the indi­vid­ual files.
    2. Con­tinue pars­ing the doc­u­ment as if it was never interrupted.
    3. Fin­ish pars­ing the doc­u­ment even if the script files have downloaded.
    4. Exe­cute each script in the order they were encoun­tered in the document.

    Reference :Difference between Async and Defer

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题