280

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?

Kamil Kiełczewski
  • 53,729
  • 20
  • 259
  • 241
Claes Gustavsson
  • 4,719
  • 7
  • 43
  • 71
  • Please post your full code. As Darin and I have said (ignore the others) this should work. There must be an error elsewhere if it's not working. – Skilldrick Jan 30 '11 at 11:38
  • 4
    all popular browsers can display javascript errors - do you get any? – Christoph Jan 30 '11 at 11:56
  • Are you running `window.onload = codeAddress` after `codeAddress()` is defined? If so, this should work. Are you sure there isn't an error elsewhere? – Skilldrick Jan 30 '11 at 11:20
  • This doesn't make any sense. window.onload runs after page load and all javascript is available, so the codeAddress() function can be declared anywhere within the page or linked js files. It doesn't have to come before unless it were called during the page load itself. – Jared Farrish Jan 30 '11 at 11:31
  • @Jared Yes it does. Have a look at http://jsfiddle.net/HZHmc/. It doesn't work. But if you move the window.onload to after the definition: http://jsfiddle.net/HZHmc/1/ it does work. – Skilldrick Jan 30 '11 at 11:35
  • A function declaration is *generally* hoisted to the top of the scope, so the function can be declared anywhere in an accessible scope. – Russ Cam Jan 30 '11 at 11:36
  • Actually, hmm. If the function is declared in the head tag, then window.onload works just fine. However, if the function is declared later (for instance, in the body tag), then it won't. My apologies, although I was partially correct. If the codeAddress function is not declared in the head, then that could be the problem. – Jared Farrish Jan 30 '11 at 11:37
  • @skilldrick - in your first exame, it doesn't work because that's a function expression that doesn't get hoisted. Change it to a function declaration (function func() {}) and it works. – Russ Cam Jan 30 '11 at 11:38
  • @Russ Yes I'm aware of that, I was just proving the point that "window.onload runs after page load and all javascript is available, so the codeAddress() function can be declared anywhere within the page or linked js files." isn't true. – Skilldrick Jan 30 '11 at 11:39
  • See my second note. I tested putting window.onload into a script tag in the head tag, and placed it before the function it was calling. It worked fine. It wasn't until I put it further down into the body that I noted it didn't work. I was wrong on that note, but I still don't think the answer above is completely right either. – Jared Farrish Jan 30 '11 at 11:43
  • 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

10 Answers10

387

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>
thesecretmaster
  • 1,887
  • 1
  • 24
  • 36
Darin Dimitrov
  • 960,118
  • 257
  • 3,196
  • 2,876
201

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);
Spencer May
  • 3,644
  • 8
  • 26
  • 46
  • 7
    (noob question: what does the `false` do?) – ᔕᖺᘎᕊ Apr 11 '15 at 17:06
  • 7
    @ᔕᖺᘎᕊ for the 'bubbles' property (which you do not have to include, I just fill in all booleans for good habit). There is also another boolean statement for 'cancelable' property, but it is not very useful since the above statement is already un-cancelable. Read more about it here: https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded – Spencer May Apr 13 '15 at 17:04
  • 1
    This is what I was looking for right now :) Executes when the DOM is complete, so you can manipulate it, not when the browser says "page completely loaded", which may take several seconds, based on external stuff (such as ads) – Nathanyel Mar 01 '17 at 08:00
  • Slightly noob question, what if you don't know if the page is loaded or not? Edit: Ah: document.readyState – Brian Hannay Apr 29 '17 at 23:13
  • 1
    @x-yuri "The DOMContentLoaded event is fired when the document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading (the load event can be used to detect a fully-loaded page)." - https://stackoverflow.com/questions/2414750/difference-between-domcontentloaded-and-load-events – Spencer May Aug 09 '17 at 17:14
  • That doesn't answer my question. It's just a matter of what you need. – x-yuri Aug 10 '17 at 11:20
  • @x-yuri ah, I understand the question now...the answer is, nothing is wrong with `window.onload` – Spencer May Aug 10 '17 at 14:56
  • 2
    `window.onload` can only be set once. If you want to run two functions at load with `window.onload`, the second one will overwrite the first. – Yay295 Aug 08 '18 at 16:13
  • Is it possible for the page to load before this listener is added, causing the listener to never fire? – ArtOfWarfare Jul 14 '20 at 01:13
  • Simple question, will this work within an IIEF? or does it make more sense to place my IIEF's within this wrapper? – klewis Sep 04 '20 at 16:57
  • 1
    @klewis since an IIEF runs immediately I can't imagine it would cause an issue if you ran the event listener inside of it...the scope would just be changed to inside the IIEF. Running the IIEF inside the event listener would make more logical sense as its best practice to have one event listener for dom readiness and call your functions from there. It's really just dependent on how you structure your code – Spencer May Sep 08 '20 at 22:15
50

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

running fiddle

$(document).ready ( function(){
   alert('ok');
});​
Eat at Joes
  • 4,374
  • 1
  • 35
  • 35
41

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.

Habeeb
  • 6,226
  • 1
  • 25
  • 29
  • 1
    This is the only code that works with HTML Preview for GitHub: https://htmlpreview.github.io/ Other code, while correct, is ruined by this HTML Preview. – Jason Doucette Jan 14 '19 at 02:55
  • 2
    Can someone explain how this is different than putting the script tags at the end of the HTML page and the purpose of the anonymous function? – user Aug 12 '19 at 00:33
  • Shouldn't the last line be `}());`? – Chewie The Chorkie Feb 23 '21 at 23:37
  • 1
    @ChewieTheChorkie. The last line is as per the answer itself, because its an IIFE (Immediately Invoked Function Expression). – Habeeb Feb 24 '21 at 07:42
12

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

Will
  • 141
  • 1
  • 5
5

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>
Kamil Kiełczewski
  • 53,729
  • 20
  • 259
  • 241
2

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);
Russ Cam
  • 117,566
  • 29
  • 193
  • 253
1

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>
Rudra
  • 13
  • 2
1

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

(*your function goes here*)(); 

Alternatively:

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

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.
}
Obaidah
  • 81
  • 1
  • 3