• Normal execution <script>

    This is the default behavior of the <script> element. Parsing of the HTML code pauses while the script is executing. For slow servers and heavy scripts this means that displaying the webpage will be delayed.


  • Deferred execution <script defer>

    Simply put: delaying script execution until the HTML parser has finished. A positive effect of this attribute is that the DOM will be available for your script. However, since not every browser supports defer yet, don’t rely on it!

  • Asynchronous execution <script async>

    Don’t care when the script will be available? Asynchronous is the best of both worlds: HTML parsing may continue and the script will be executed as soon as it’s ready. I’d recommend this for scripts such as Google Analytics.
    • 单线程的 => 意味着js执行时,htmlparse会暂停。

问题1
  • 动态插入的script标签 a ,在静态script标签 b之前。但是a设置defer,那么谁先执行?
分析:
  • 静态标签是parse到时立即执行,defer的标签是parse完成最后执行。
  • 具有defer属性的多个script标签之间执行顺序和html顺序一致
结论:
  • b先执行,a后执行。

问题2:
  • 动态插入的script标签a的async = false,那么怎么执行?
分析:
  • 默认情况动态插入的script标签的async属性是true
结论:
  • ????和添加defer属性一样?


目前用defer或者动态插入标签时的设置async=false来达到最后执行js的方法都有问题(不知道问题哪里?)
但是可以如下解决:
总体结论:
  • 要延迟执行可以直接通过监听DOMContentLoaded事件来动态插入script标签。(这样肯定不会出现问题)


动态插入script标签:动态插入script标签:






async/defer/normal excute <script>标签

2019-02-16 21:53:46 0 39
这里是评论

相关推荐