How to run a function when the page is loaded?

JavascriptHtmlOnload

Javascript Problem Overview


I want to run a function when the page is loaded, but I don’t want to use it in the <body> tag.

I have a script that runs if I initialise it in the <body>, like this:

function codeAddress() {
  // code
}

<body onLoad="codeAddress()">

But I want to run it without the <body onload="codeAddress()"> and I have tried a lot of things, e.g. this:

window.onload = codeAddress;

But it is not working.

So how do I run it when the page is loaded?

Javascript Solutions


Solution 1 - Javascript

window.onload = codeAddress; should work - here's a demo, and the full code:

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


<!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');
        }
        
        </script>
    </head>
    <body onload="codeAddress();">
    
    </body>
</html>

Solution 2 - Javascript

Rather than using jQuery or window.onload, native JavaScript has adopted some great functions since the release of jQuery. All modern browsers now have their own DOM ready function without the use of a jQuery library.

I'd recommend this if you use native Javascript.

document.addEventListener('DOMContentLoaded', function() {
    alert("Ready!");
}, false);

Solution 3 - Javascript

Taking Darin's answer but jQuery style. (I know the user asked for javascript).

running fiddle

$(document).ready ( function(){
   alert('ok');
});​

Solution 4 - Javascript

Alternate solution. I prefer this for the brevity and code simplicity.

(function () {
    alert("I am here");
})();

This is an anonymous function, where the name is not specified. What happens here is that, the function is defined and executed together. Add this to the beginning or end of the body, depending on if it is to be executed before loading the page or soon after all the HTML elements are loaded.

Solution 5 - Javascript

window.onload = function() { ... etc. is not a great answer.

This will likely work, but it will also break any other functions already hooking to that event. Or, if another function hooks into that event after yours, it will break yours. So, you can spend lots of hours later trying to figure out why something that was working isn't anymore.

A more robust answer here:

if(window.attachEvent) {
    window.attachEvent('onload', yourFunctionName);
} else {
    if(window.onload) {
        var curronload = window.onload;
        var newonload = function(evt) {
            curronload(evt);
            yourFunctionName(evt);
        };
        window.onload = newonload;
    } else {
        window.onload = yourFunctionName;
    }
}

Some code I have been using, I forget where I found it to give the author credit.

function my_function() {
    // whatever code I want to run after page load
}
if (window.attachEvent) {window.attachEvent('onload', my_function);}
else if (window.addEventListener) {window.addEventListener('load', my_function, false);}
else {document.addEventListener('load', my_function, false);}

Hope this helps :)

Solution 6 - Javascript

Try readystatechange

document.addEventListener('readystatechange', () => {    
  if (document.readyState == 'complete') codeAddress();
});

where states are:

  • loading - the document is loading (no fired in snippet)
  • interactive - the document is parsed, fired before DOMContentLoaded
  • complete - the document and resources are loaded, fired before window.onload

<script>
  document.addEventListener("DOMContentLoaded", () => {
    mydiv.innerHTML += `DOMContentLoaded (timestamp: ${Date.now()})</br>`;
  });
  
  window.onload = () => {
    mydiv.innerHTML += `window.onload (timestamp: ${Date.now()}) </br>` ;
  } ;

  document.addEventListener('readystatechange', () => {
    mydiv.innerHTML += `ReadyState: ${document.readyState}  (timestamp: ${Date.now()})</br>`;
    
    if (document.readyState == 'complete') codeAddress();
  });

  function codeAddress() {
    mydiv.style.color = 'red';
  }
</script>

<div id='mydiv'></div>

Solution 7 - Javascript

Take a look at the domReady script that allows setting up of multiple functions to execute when the DOM has loaded. It's basically what the Dom ready does in many popular JavaScript libraries, but is lightweight and can be taken and added at the start of your external script file.

Example usage

// add reference to domReady script or place 
// contents of script before here

function codeAddress() {

}

domReady(codeAddress);

Solution 8 - Javascript

window.onload will work like this:

function codeAddress() {
	document.getElementById("test").innerHTML=Date();
}
window.onload = codeAddress;

<!DOCTYPE html>
<html>
<head>
	<title>learning java script</title>
	<script src="custom.js"></script>
</head>
<body>
	<p id="test"></p>
	<li>abcd</li>
</body>
</html>

Solution 9 - Javascript

As soon as the page load the function will be ran:

(*your function goes here*)(); 

Alternatively:

document.onload = functionName();
window.onload = functionName(); 

Solution 10 - Javascript

I believe this is the best way to maintain support across different versions of browsers

if (window.addEventListener) {
   window.addEventListener("load", myFunction, false);
}
else if (window.attachEvent) {
   window.attachEvent("onload", myFunction);
}
else {
   window.onload = myFunction; //will override previously attached event listeners.
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionClaes GustavssonView Question on Stackoverflow
Solution 1 - JavascriptDarin DimitrovView Answer on Stackoverflow
Solution 2 - JavascriptSpencer MayView Answer on Stackoverflow
Solution 3 - JavascriptEat at JoesView Answer on Stackoverflow
Solution 4 - JavascriptHabeebView Answer on Stackoverflow
Solution 5 - JavascriptWillView Answer on Stackoverflow
Solution 6 - JavascriptKamil KiełczewskiView Answer on Stackoverflow
Solution 7 - JavascriptRuss CamView Answer on Stackoverflow
Solution 8 - JavascriptRudraView Answer on Stackoverflow
Solution 9 - JavascriptfruitloafView Answer on Stackoverflow
Solution 10 - JavascriptObaidahView Answer on Stackoverflow