Javascript: 在脚本运行之前不要完成页面加载

Javascript: don't finish loading page until script runs

我有一个脚本可以在存在特定查询字符串时替换网页的 HTML。脚本需要在 HTML 之后加载,但必须是 运行 并在页面完成加载之前更新 HTML,以便我的外部脚本检测页面内容。有办法实现吗?

我制作了这个时间线图来显示事件应该发生的时间。


  +--------------------------------+
  | |                              |
E |=• Page begins loading          |
v | |                              |
e |=====• Script runs and          |
n | |     website content changes  |
t | |                              |
  |=========• Page is loaded       |
  | |                              |
  +--------------------------------+
    ^   ^   ^      Time
    1   2   3

使用属性 defer 包含您的脚本。

<script src="./path/to/my/script.js" defer></script>

Scripts with the defer attribute will prevent the DOMContentLoaded event from firing until the script has loaded and finished evaluating

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script