366

Traditionally, to call a JavaScript function once the page has loaded, you'd add an onload attribute to the body containing a bit of JavaScript (usually only calling a function)

<body onload="foo()">

When the page has loaded, I want to run some JavaScript code to dynamically populate portions of the page with data from the server. I can't use the onload attribute since I'm using JSP fragments, which have no body element I can add an attribute to.

Is there any other way to call a JavaScript function on load? I'd rather not use jQuery as I'm not very familiar with it.

Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
palAlaa
  • 9,500
  • 33
  • 107
  • 166
  • Can you either verify that Kevin's edit to your question is still asking the same question, or rephrase it to make sure we understand? (Are you trying to find an alternative to onload?) – STW Oct 01 '10 at 20:06
  • 1
    Does this answer your question? [How to make JavaScript execute after page load?](https://stackoverflow.com/questions/807878/how-to-make-javascript-execute-after-page-load) – T.Todua Feb 09 '21 at 21:08

8 Answers8

560

If you want the onload method to take parameters, you can do something similar to this:

window.onload = function() {
  yourFunction(param1, param2);
};

This binds onload to an anonymous function, that when invoked, will run your desired function, with whatever parameters you give it. And, of course, you can run more than one function from inside the anonymous function.

ˈvɔlə
  • 9,204
  • 10
  • 63
  • 89
Matt Sieker
  • 9,349
  • 2
  • 25
  • 43
  • And now when I'm dynamically including a server-generated page and need DOM-readiness, I need to work through this minefield. If only someone would have encouraged properly library user earlier. – Stefan Kendall Oct 01 '10 at 21:27
  • 4
    I didn't say it was a good idea. Though the lead dev where I work has a strong case of Not Invented Here syndrome, and I haven't been able to convince him to use jquery, outside of a few pages. – Matt Sieker Oct 01 '10 at 21:46
  • 3
    Then perhaps you should switch jobs. If the right tool for the job isn't the tool you're using, why beat your head against the wall constantly battling the incompetent? – Stefan Kendall Oct 01 '10 at 22:09
  • And can I call the same yourfunction second time using onclick event on button? – Faizan Nov 07 '13 at 14:34
  • 4
    If another script has already loaded a function on window.onload, this method will override it. This could an issue in some cases. The document.addEventListener approach seems preferable to me. – kaore Mar 11 '21 at 11:21
  • Just a tip. Document.onload() is used when the DOM is fully loaded, whereas Window.onload() is used when the graphical part is loaded for presentation. Document.onload is pretty much just behind-the-scenes, so I recommend using that if possible, since it uses none of your cpu...or gpu, I don't know, I looked this up. – crjase Nov 20 '22 at 09:49
141

Another way to do this is by using event listeners, here's how you use them:

document.addEventListener("DOMContentLoaded", function() {
  your_function(...);
});

Explanation:

DOMContentLoaded It means when the DOM objects of the document are fully loaded and seen by JavaScript. Also this could have been "click", "focus"...

function() Anonymous function, will be invoked when the event occurs.

Matthias Braun
  • 32,039
  • 22
  • 142
  • 171
Ahmed Jolani
  • 2,872
  • 2
  • 20
  • 24
  • 7
    Note that this will not work in IE 8 and lower. Otherwise this is the best pure JS solution! – Philipp May 20 '15 at 10:57
  • This is the correct answer as the accepted answer would lead to conflicts if there's more than one method to be called on load. – mapto Apr 15 '22 at 08:50
72

Your original question was unclear, assuming Kevin's edit/interpretation is correct, then this first option doesn't apply

The typical options is using the onload event:

<body onload="javascript:SomeFunction()">
....

You can also place your JavaScript at the very end of the body; it won't start executing until the doc is complete.

<body>
  ...
  <script type="text/javascript">
    SomeFunction();
  </script>
</body>

Another option is to use a JS framework which intrinsically does this:

// jQuery
$(document).ready( function () {
  SomeFunction();
});
Matthias Braun
  • 32,039
  • 22
  • 142
  • 171
STW
  • 44,917
  • 17
  • 105
  • 161
52
function yourfunction() { /* do stuff on page load */ }

window.onload = yourfunction;

Or with jQuery if you want:

$(function(){
   yourfunction();
});

If you want to call more than one function on page load, take a look at this article for more information:

Philipp
  • 10,240
  • 8
  • 59
  • 71
Sarfraz
  • 377,238
  • 77
  • 533
  • 578
  • 4
    This is not correct, the function will execute and assign whatever it returns to onload. The () should not be there. – epascarello Oct 01 '10 at 20:02
  • 2
    If there are other functions that are listening for the onload event this will blow them away. Better to add an event listener rather than assign an event handler directly. Even in this case you would assign it as `window.onload = yourfunction' without the function closure, not the way you have it. Your way seeks to execute yourfunction() at the time of the assignment. – Robusto Oct 01 '10 at 20:03
  • that will assign the return value of the function to window.onload, which will not work, unless the return value is a function. – I.devries Oct 01 '10 at 20:03
  • @epascarello: Good catch, fixed, you see a habit when writing function names. Thanks – Sarfraz Oct 01 '10 at 20:03
  • 1
    window.onload = yourfunction; The problem with this way is that it dosen't accept fucntion parameter !! – palAlaa Oct 01 '10 at 20:13
  • I'm afraid that as of June 2020, the linked resource seems to be dead. This one still works: [Using Multiple JavaScript Onload Functions](http://www.brefere.com/fbapps/bcom.nsf/cvbdate/D514491209EE5C848725801A0074AE6E?opendocument#:~:text=Using%20Multiple%20JavaScript%20Onload%20Functions,have%20an%20existing%20onload%20event%3F) – Gwyneth Llewelyn Jun 19 '20 at 11:12
14

<!DOCTYPE html>
<html>
    <head>
        <title>Test</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <script type="text/javascript">
        function codeAddress() {
            alert('ok');
        }
        window.onload = codeAddress;
        </script>
    </head>
    <body>
    
    </body>
</html>
anonymous
  • 157
  • 1
  • 2
  • 3
    I think his answer is clear, as you can see the script is put in the head tag thus allowing it to be executed before the body content.. or let's say preload its functions or whatever.. sometimes a person ask questions because he don't know at all, but it's never the case where someone would spoon feed you, nor anyone in this community would, you have to look up stuff yourself a little bit more. #especially_that_you're_a_web_developer – Viktova Jul 22 '18 at 07:04
9

You have to call the function you want to be called on load (i.e., load of the document/page). For example, the function you want to load when document or page load is called "yourFunction". This can be done by calling the function on load event of the document. Please see the code below for more detail.

Try the code below:

<script src="js/jquery-1.11.0.min.js" type="text/javascript"></script>
<script type="text/javascript">

    $(document).ready(function () {
        yourFunction();
    });
    function yourFunction(){
      //some code
    }
</script>
Amir Md Amiruzzaman
  • 1,911
  • 25
  • 24
6

here's the trick (works everywhere):

r(function(){
alert('DOM Ready!');
});
function r(f){/in/.test(document.readyState)?setTimeout('r('+f+')',9):f()}
Abhishek
  • 674
  • 6
  • 9
1

For detect loaded html (from server) inserted into DOM use MutationObserver or detect moment in your loadContent function when data are ready to use

let ignoreFirstChange = 0;
let observer = (new MutationObserver((m, ob)=>
{
  if(ignoreFirstChange++ > 0) console.log('Element added on', new Date());
}
)).observe(content, {childList: true, subtree:true });


// TEST: simulate element loading
let tmp=1;
function loadContent(name) {  
  setTimeout(()=>{
    console.log(`Element ${name} loaded`)
    content.innerHTML += `<div>My name is ${name}</div>`; 
  },1500*tmp++)
}; 

loadContent('Senna');
loadContent('Anna');
loadContent('John');
<div id="content"><div>
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345