0

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
    }
  }
}
Nick Parsons
  • 31,322
  • 6
  • 25
  • 44
C. Doe
  • 19
  • 3
  • 7
    Possible duplicate of [How to run a function when the page is loaded?](https://stackoverflow.com/questions/4842590/how-to-run-a-function-when-the-page-is-loaded) – adiga Feb 07 '19 at 11:41

2 Answers2

2

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

    }


  }
}
ellipsis
  • 11,498
  • 2
  • 13
  • 33
0

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);
nick zoum
  • 6,639
  • 5
  • 26
  • 63