When to use async vs defer when loading scripts?

前端 未结 1 1669
后悔当初
后悔当初 2021-02-20 01:53

So I\'ve recently learned that putting your js at the bottom of the DOM is antiquated, and that I should be once again putting them in the with the “as

1条回答
  •  爱一瞬间的悲伤
    2021-02-20 02:27

    It's quite simple. You should use [async] for scripts which can be executed in any order, and [defer] for scripts which have to be executed after HTML is parsed.

    For example, if you have a script that add social sharing icons next to your posts, and this script doesn't rely on any other script, you can use both [async] and [defer]. But if your scripts requires jQuery, you can't use [async], because if you do, it might turn out that it gets executed before jQuery is loaded and it breaks.

    If all your scripts require jQuery, then you shouldn't use [async] at all. As for [defer], it depends on whether your scripts access DOM. For plugins it probably doesn't matter, but you'll probably need it for your own code.

    If you wrap your scripts in $(document).ready();, you can use [defer] for scripts which don't have immediate effect (e.g. require user interaction).

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