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

标签 javascript html loading

我有一个脚本,如果存在某个查询字符串,它会替换网页的 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

关于Javascript:在脚本运行之前不要完成页面加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52582630/

相关文章:

javascript - 使用 React 时,在构造函数中使用粗箭头函数还是绑定(bind)函数更可取?

javascript - JQGrid 'Change' dataevent 在更改函数内更改网格行数据后未触发

html - 为什么粉色框在IE6中不重叠?

php - 为什么使用 cookie 通过 php 安全风险输出 html?

angularjs - 将 'isLoading' 变量添加到 $resource 服务( Angular )

javascript - "The entity name must immediately follow the ' & ' in the entity reference."

javascript - 来自表单的 HTML 标记生成器

php - 如何让 PHP 回显 XML 标签?

javascript - 如何显示加载图标直到等待完成

javascript - 是否有函数可以查找当前使用 XMLHtttpRequest 从文件加载的字节数?