[英]I need help to place a function so my code runs after the DOM has been rendered
I have a line of code that runs faster than the DOM so I need a timeout-function but I don't know where to put it. 我有一行代码比DOM运行得更快,因此我需要一个超时功能,但我不知道将其放在哪里。
function testing() {
var newHeadline = document.createElement("h1");
newHeadline.textContent = "Headline";
document.getElementsByClassName("col-sm")[0].insertBefore(newHeadline, document.getElementsByClassName("text-content")[0]);
for (var a = 0; a < 10; a++) {
if (document.getElementsByClassName("form-control")[0] != undefined) {
document.getElementsByClassName("form-control")[0].parentElement.remove();
return true
}
}
}
Use window.onload. 使用window.onload。 window.onload ensures that first everything in the window including scripts and images have been loaded, and after everything is loaded it call the function which is supplied.
window.onload确保首先加载窗口中的所有内容,包括脚本和图像,然后加载所有内容,然后调用提供的函数。
window.onload=function testing() { var newHeadline = document.createElement("h1"); newHeadline.textContent = "Headline"; document.getElementsByClassName("col-sm")[0].insertBefore(newHeadline, document.getElementsByClassName("text-content")[0]); for (var a = 0; a < 10; a++) { if (document.getElementsByClassName("form-control")[0] != undefined) { document.getElementsByClassName("form-control")[0].parentElement.remove(); return true } } }
Use the DOMContentLoaded
event if you want to wait until all HTML has been loaded and JavaScript has been parsed, or the load
event if you also want to wait until all the images and styles have been applied. 如果要等待直到所有HTML都已加载并且解析了JavaScript,请使用
DOMContentLoaded
事件;如果也要等待所有图像和样式都已应用,请使用load
事件。
if (document.readyState === "complete") testing();
else addEventListener("DOMContentLoaded", testing);
OR 要么
if (document.readyState === "complete") testing();
else addEventListener("load", testing);
You can also use an empty timeout
, to run the function right after the script has been parsed and run. 您还可以使用一个空的
timeout
,在脚本被解析并运行之后立即运行该函数。
setTimeout(testing, 0);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.