[英]Can I use document.getElementById() before the DOM is fully loaded?
I want to know if it is correct to use document.getElementById()
before the DOM is fully loaded.我想知道在 DOM 完全加载之前使用document.getElementById()
是否正确。
I mean, under the definition of the DOM element.我的意思是,根据DOM 元素的定义。
Example :示例:
<html>
<head>...
<body>
<div id="hello">...
...
<script>
document.getElementById('hello')...
</script>
...
I tried it and it works, but I want to know if it's okay to do so.我试过了,它有效,但我想知道这样做是否可以。
I am aware that I can listen to the DOM load event and act depending on it, but I don't want to do that if it's not strictly necessary.我知道我可以监听 DOM 加载事件并根据它采取行动,但如果不是绝对必要的,我不想这样做。
It's perfectly fine to do that.这样做完全没问题。 Scripts are often placed at the end of the <body>
tag, so you don't have to wait for the DOM load event.脚本通常放置在<body>
标签的末尾,因此您不必等待 DOM 加载事件。
Prefer to do this way:更喜欢这样做:
<html>
<head>...
<body>
<div id="hello">
...
<script>
const myHello = document.getElementById('hello');
myHello.onclick=evt=>
{
...
}
</script></body></html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.