Categories
html javascript onload

How to run a function when the page is loaded?

311

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?

11

  • Are you running window.onload = codeAddress after codeAddress() is defined? If so, this should work. Are you sure there isn’t an error elsewhere?

    Jan 30, 2011 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.

    Jan 30, 2011 at 11:31

  • @Jared Yes it does. Have a look at jsfiddle.net/HZHmc. It doesn’t work. But if you move the window.onload to after the definition: jsfiddle.net/HZHmc/1 it does work.

    Jan 30, 2011 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, 2011 at 11:36

  • 4

    all popular browsers can display javascript errors – do you get any?

    – Christoph

    Jan 30, 2011 at 11:56

415

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>

5

  • 4

    As I said in my answer, there’s nothing wrong with the code as seen – the reason it’s not working must be an error in the JS somewhere.

    Jan 30, 2011 at 11:27

  • if you put a paragraph with text in the body, it will not load until you click ok.

    Sep 22, 2016 at 12:59

  • This global event handler is only available in Chrome. developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/…

    Jan 28, 2017 at 1:36

  • 1

    the problem with this is that you may override previous onload functions. Use an event listener instead

    Sep 9, 2020 at 8:46

  • would something like this be better now? window.onload = () => {alert("ok");}

    May 9 at 17:05

236

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

11

  • 11

    (noob question: what does the false do?)

    Apr 11, 2015 at 17:06

  • 9

    @ᔕᖺᘎᕊ 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: developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded

    Apr 13, 2015 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 1, 2017 at 8:00

  • 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).” – stackoverflow.com/questions/2414750/…

    Aug 9, 2017 at 17:14

  • 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 8, 2018 at 16:13

51

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

running fiddle

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

2

  • 6

    Your answer taught me allot, but not about jQuery / javascript.

    – unicorn2

    Mar 23, 2015 at 14:32

  • 2

    @VijayKumar this is jQuery, not native Javascript so you need a jQuery library included for it to work

    Oct 2, 2015 at 13:44