如果我在 body
标签的末尾放置一个带有相应 JS 文件的 script
标签,我是否应该等待 DOMContentLoaded
事件?
index.html
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" type="text/css" href="popup.css">
</head>
<body>
<div id="container"></div>
<script src="popup.js"></script>
</body>
</html>
popup.js
document.addEventListener('DOMContentLoaded', onDOMContentLoaded);
最佳答案
基本上没有。如果脚本修改元素,它需要存在。
如果您将脚本放在该元素之后,它就会存在。
如果你把它放在之前,它不存在,你可能想使用 DOMContentLoaded 等待脚本执行,直到它确定它存在。
<div id="myid"></div>
<script>
getElementById('myid'); // it will work, Element myid Is defined
<script>
但是这个
<script>
getElementById('myid'); // it will fail, it's not yet defined, it will be
// Using DomContentLoaded here would be requrired
<script>
<div id="myid"></div>
关于javascript - 如果我在 body 标签的末尾放置一个脚本标签,我应该等待 DOMContentLoaded 事件吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34807614/