Marcelo Camargo
Marcelo Camargo

Reputation: 2298

Document OnLoad isn't working

I have an object with a main function in JS and I want to call it when the document loads, but not as an attribute of body. My code is the following:

var program = {
    main: function(args) {
        alert(args)
    }
}

document.onload = function() {
    program.main("xyz")
}

But I really don't understand why in the world it doesn't work. Can you guys give me some help to do it work?

And in my HTML:

<!DOCTYPE html>
<html>
    <head>
        <script src="./libs/file.js" type="text/javascript"></script>
    </head>
    <body>

    </body>
</html>

Upvotes: 0

Views: 534

Answers (1)

nepeo
nepeo

Reputation: 509

@Huangism is right about attaching the on load to the window not the document. I use this combination for most of my page set ups, allows you to start async file loads etc earlier than on load and then change DOM content after on load.

(function preLoad(){  /*runs before content is loaded, rest of content won't load until this has completed*/

window.addEventListener('load', function(){onLoad();}, false);
}());

function onLoad(){  /*runs after content is loaded and page has loaded*/


};

Also neatly packages your set up functions, easy to maintain and read! :)

Upvotes: 1

Related Questions