Note that there are some explanatory texts on larger screens.

plurals
  1. POFunction that executes once and only when an element is fully loaded
    primarykey
    data
    text
    <p>I'm having a bit of difficulty getting a JavaScript function to execute <em>once</em> and only when a DOM element is fully loaded. I've tried countless combindations of <code>setInterval</code>s, <code>seTimeout</code>s, <code>FOR</code> loops, <code>IF</code> statements, <code>WHILE</code> loops, etc and gotten nowhere.</p> <p>I did manage to get it to work once, but it's hit-and-miss as I could only get it to work by delaying the function by 2 seconds (which isn't good, as there's no telling exactly how long it takes to load) and rapidly re-firing the same function over and over, which also isn't good.</p> <p>I just need something to constantly scan the page to tell whether an element exists and has content (<code>innerHTML != undefined</code>, or something), execute a block of code as soon as it is loaded (and only once) and then stop scanning the page.</p> <p>Has anyone found a way to do this? Also, I need JavaScript, not jQuery.</p> <p>Thanks. <br /><br /> <strong>Original Code</strong></p> <pre><code>function injectLink_Bridge(){ setTimeout(function(){ injectLink(); }, 2000); } function injectLink(){ var headerElement = document.getElementsByClassName("flex-module-header"); if (headerElement.innerHTML == undefined) { console.log("Element doesn't exist. Restarting function"); setTimeout(function(){ injectLink_Bridge(); //I can't remember if the bridge is necessary or not }, 2000); } else { console.log("Element exists. Injecting"); setTimeout(function(){ headerElement[1].innerHTML += "code" //Inject code into the second instance of the class-array }, 2000); } } </code></pre> <p><strong>Finished code</strong></p> <pre><code>function injectLink(){ var headerElement = document.getElementsByClassName("flex-module-header")[1]; //Get the second instance if(headerElement &amp;&amp; headerElement.innerHTML != ""){ console.log("Element exists and has content. Injecting code..."); headerElement.innerHTML += "code"; //Currently revising, due to T.J. Crowder's side-note } else { console.log("Element doesn't exist or has no content. Refiring function..."); setTimeout(injectLink, 250); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload