开发者

How to call JavaScript function from body of HTML document on pageload-complete

开发者 https://www.devze.com 2023-03-04 16:40 出处:网络
I have some JavaScript (code to initialize Google Maps if you\'re interested) that I\'m forced to include within the <body></body> tags of an html document and I would like to have one of

I have some JavaScript (code to initialize Google Maps if you're interested) that I'm forced to include within the <body></body> tags of an html document and I would like to have one of my methods trigger on page-load complete. The catch is that I don't have access to the <body> html tag, so I can't do:

<body on开发者_开发问答load="foo()"> 

Is there any way to accomplish this? I realize this is a ridiculous scenario.


Depending on when the code is run, attach the handler with JavaScript:

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

As you seem to have no control over the page we have to be a bit more careful. Other JavaScript might already have set an event handler. To be a good citizen, we don't just overwrite the event handler, but keep a reference to it in case it exists.

However other JavaScript code could overwrite this again.

The best way would be to use the more advanced event handling methods addEventListener (W3C) and attachEvent (IE).

For more information about event handling I suggest to read the excellent articles on quirksmode.org.


If you are using jQuery you can use $(document).ready:

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

See this tutorial.


window.onload = foo;

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


You can programattically attach events using the DOM.

// Function to add event listener to body 

function addLoadFn() 
{ 
   var body = document.getElementById("body"); 
   body.addEventListener("load", myOnloadListener, false); 
}
0

精彩评论

暂无评论...
验证码 换一张
取 消