Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

dom

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.

like image 538
2hamed Avatar asked May 24 '11 18:05

2hamed


People also ask

How do I run a function after page load?

The first approach for calling a function on the page load is the use an onload event inside the HTML <body> tag. As you know, the HTML body contains the entire content of the web page, and when all HTML body loads on the web browser, it will call the function from the JavaScript.

How do I run a script after DOM loaded?

The Easiest Way: place script at the end of body The fastest way to go about this in JavaScript is to run a self-executing function in a script appended at the end of the <body> element. Because the script runs at the end of the <body> element, it will only run after all the DOM is processed and loaded onto the page.

What are the ways to execute JavaScript after page load?

Using "defer" readyState = "interactive") and just before "DOMContentLoaded" Event is triggered. If you need to execute the script after all resources (images, scripts) are loaded use "load" event or target one of the document.

How do you call a function before page loads?

The earliest point at which you can run a Javascript function with access to the DOM (without waiting for page load) is by placing a <script> tag right after the opening <body> tag. Scripts inside the <head> will run before this occurs, but there won't be access to the elements on the page.


1 Answers

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);
  }
}
like image 61
mVChr Avatar answered Oct 22 '22 15:10

mVChr