简体   繁体   中英

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.

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 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=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.

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.

setTimeout(testing, 0);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM