[javascript] How to run a function when the page is loaded?

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?

This question is related to javascript html onload

The answer is


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 :)


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

(*your function goes here*)(); 

Alternatively:

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

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

running fiddle

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

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

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

_x000D_
_x000D_
<script>_x000D_
  document.addEventListener("DOMContentLoaded", () => {_x000D_
    mydiv.innerHTML += `DOMContentLoaded (timestamp: ${Date.now()})</br>`;_x000D_
  });_x000D_
  _x000D_
  window.onload = () => {_x000D_
    mydiv.innerHTML += `window.onload (timestamp: ${Date.now()}) </br>` ;_x000D_
  } ;_x000D_
_x000D_
  document.addEventListener('readystatechange', () => {_x000D_
    mydiv.innerHTML += `ReadyState: ${document.readyState}  (timestamp: ${Date.now()})</br>`;_x000D_
    _x000D_
    if (document.readyState == 'complete') codeAddress();_x000D_
  });_x000D_
_x000D_
  function codeAddress() {_x000D_
    mydiv.style.color = 'red';_x000D_
  }_x000D_
</script>_x000D_
_x000D_
<div id='mydiv'></div>
_x000D_
_x000D_
_x000D_


window.onload will work like this:

_x000D_
_x000D_
function codeAddress() {_x000D_
 document.getElementById("test").innerHTML=Date();_x000D_
}_x000D_
window.onload = codeAddress;
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
 <title>learning java script</title>_x000D_
 <script src="custom.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
 <p id="test"></p>_x000D_
 <li>abcd</li>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_


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

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.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to onload

iFrame onload JavaScript event Execute write on doc: It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened. How to run function in AngularJS controller on document ready? Cannot set property 'innerHTML' of null Javascript onload not working Trying to fire the onload event on script tag How to execute AngularJS controller function on page load? Add Class to Object on Page Load How to run a function when the page is loaded? jquery get height of iframe content when loaded