简体   繁体   中英

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

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.

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);
  }
}

Well you can utilize the document.onload and window.onload methods
For example:

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

Putting your script just 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.

Another option is adding <img src="" onerror="callback()"> after the element and execute codes on onerror event:

 function func(img) { console.log("Element loaded"); img.parentNode.removeChild(img); document.getElementById('hello').innerHTML = "Just loaded"; }
 <p id="hello">Not loaded yet</p> <img onerror="func(this)" src="" style="display:none">

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