How to call javascript function from body of HTML document in pageload-complete

I have javascript (code for initializing Google maps, if you are interested), which I have to include in the tags of an <body></body>html document, and I would like one of my methods to run on the page - the load is complete. The trick is that I do not have access to the <body>html tag , so I cannot do this:

<body onload="foo()"> 

Is there any way to do this? I understand that this is a funny scenario. Thank!

+3
source share
4 answers

Depending on when the code is executing, attach the handler using JavaScript:

if(window.onload) {
    var _existing = window.onload;
    window.onload = function() {
        _existing();
        foo();
    };
}
else {
    window.onload = foo;
}

, , , . , JavaScript . , , .

JavaScript .

addEventListener (W3C) attachEvent (IE).

quirksmode.org.

+4

DOM.

// Function to add event listener to body 

function addLoadFn() 
{ 
   var body = document.getElementById("body"); 
   body.addEventListener("load", myOnloadListener, false); 
}
+2
window.onload = foo;

function foo(){
  alert("page loaded!");
}
+2

jQuery, $(document).ready:

 $(document).ready(function() {
   // put all your jQuery goodness in here.
 });

tutorial.

+2

All Articles