onload - How do I call a JavaScript function on page load?

ID : 10162

viewed : 32

Tags : javascriptonloadjavascript

Top 5 Answer for onload - How do I call a JavaScript function on page load?

vote vote


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.

vote vote


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

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


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.

vote vote


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


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:

vote vote


<!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>

Top 3 video Explaining onload - How do I call a JavaScript function on page load?