且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

这是HTML页面中元素的加载,呈现和执行顺序?

更新时间:2023-12-04 18:51:04

我相信订单是这样的:


  1. 下载HTML文档

  2. 开始 HTML 解析

  3. 开始下载外部文件

  4. 下载外部文件(或者如果它们是内联且不需要下载),可以解析外部文件

    • 如果文件是脚本,则按照它们在HTML

      • 中显示的顺序运行它们DOM现在,他们会在运行时抛出错误

      • ,他们会阻止任何其他渲染,这就是为什么有些脚本放在正文的底部


  1. Download HTML document
  2. Start HTML Parsing
  3. Start downloading external files (JavaScript, CSS, images) as they're encountered in the HTML
  4. Parse external files once they are downloaded (or if they are inline and don't require downloading)
    • if the files are scripts, then run them in the order they appear in the HTML
      • if they try to access the DOM right now, they will throw an error
      • while they run, they will prevent any other rendering, which is why some scripts are put at the bottom of the body

  • 时执行 DOMContentLoaded 事件,即使所有其他外部文件css)未完成下载(从第4步开始)

  • 在Chrome F12开发者工具中,这由网络视图上的蓝线表示

  • 将开始运行您添加到此事件的任何内容,例如 window.addEventListener(DOMContentLoaded,doStuff,true);

  • happens even if all other external files (images, css) are not done downloading (from step 4)
  • in the Chrome F12 developer tools this is represented by a blue line on the Network view
  • will start running anything you've added to this event, e.g. window.addEventListener("DOMContentLoaded", doStuff, true);

  • 这是由网络视图

  • 上的红线表示的,这将开始运行jQuery ready 函数 $(document).ready(function(){...});

  • 将开始运行您添加到此事件的任何代码,例如 window.addEventListener(load,doStuff,true);

  • in the Chrome F12 developer tools this is represented by a red line on the Network view
  • this will start running the jQuery ready function $(document).ready(function(){ ... });
  • will start running any code you've added to this event, e.g. window.addEventListener("load", doStuff, true);

请注意,动态添加到您的网页的脚本的执行顺序(通过其他脚本)是复杂的,基本上不确定。 (请参阅此处的解答加载和执行脚本顺序

Note that the execution order of scripts that are dynamically added to your page (by other scripts) is complicated and basically indeterminate. (See the answers here load and execute order of scripts)