如何在元素加载后告诉 JavaScript 执行函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6115026/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:17:04  来源:igfitidea点击:

How to tell JavaScript to execute a function after an element has been loaded?

javascriptdom

提问by Hamed Momeni

How to tell JavaScript to execute a function after an element has been loaded w/out any external library?
Normally I have to bring the <script>tag after the element itself to work with DOM calls.

在没有任何外部库的情况下加载元素后,如何告诉 JavaScript 执行函数?
通常我必须将<script>标签放在元素本身之后才能使用 DOM 调用。

采纳答案by Naftali aka Neal

Well you can utilize the document.onloadand window.onloadmethods
For example:

那么你可以使用document.onloadwindow.onload方法
例如:

window.onload = function(){
   //do some stuff 
}

回答by mVChr

If you don't want to wait for the full page to load you can also poll for the element's existence:

如果您不想等待整个页面加载,您还可以轮询元素的存在:

function myFunc() {
  if (document.getElementById('myElement')) {
    // do stuff
  } else {
    setTimeout(myFunc, 15);
  }
}

回答by James Hill

Putting your scriptjust above the body tag is a valid option. If the element in question supports it, you can also use it's onload event. You could also attach to the onload event of the window or document.

将您的脚本放在body 标签上方是一个有效的选择。如果有问题的元素支持它,您也可以使用它的 onload 事件。您还可以附加到窗口或文档的 onload 事件。