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