开发者

Alternative to <body onload="init ();">

I'm trying to fix an old script written for me. I need it to run without <body onload="init ();">. I'd like to run the function from insi开发者_如何学Pythonde the script without inline code like that command. Sorry I'm not a JS expert but how do I do this?


<script type="text/javascript">
    function init() {
        // Put your code here
    }
    window.onload = init;
</script>

Or, if you are using jQuery:

$(function() {
    // Your code here
});


In a pure JavaScript implementation, you'd want to wait for the page to be ready to invoke your events. The simplest solution is like so:

<script type="text/javascript" language="javascript">
      window.onload = function()
      {
          init();
      };
</script>

But that's not much better than your original implementation via placing that on the tag itself. What you can do is wait for a specific event though:

 document.addEventListener("DOMContentLoaded", function()
 {
     init();
 }, false);

This should be fired a little earlier in the cycle and should do nicely.

Additionally, if you are using jQuery, you can simply add a function to be executed when that event is fired using the simple syntax:

 $(document).ready(function() // or $(function()
 {
     init();
 });


Here's a slight variation on Tejs' response. I often find it more readable and manageable to separate the init() function from the code registering the event handler:

function init(e) {

    //statements...

}

document.addEventListener('DOMContentLoaded', init, false);

Also, in place of an explicit init() function, I've sometimes used a self-executing anonymous function placed at the very, very bottom of the page, just before the </body> tag:

(function() {

    //statements...

})();


best option is to just put the call to init() at the bottom of the page:

<html>

<head>
...
</head>

<body>
.... page content here ...
<script type="text/javascript">init();</script>
</body>
</html>

By placing it at the bottom like that, you'll be sure that it runs as pretty much the very last thing on the page. However, note that it's not as reliable as using the onload option in the body tag, or jquery's $('document').ready() or mootool's window.addEvent('domready', ...).


<script type="text/javascript">
    function init() {
        // Put your code here
    }
    window.onload = init;
</script>

it is not work should be use this

<script type="text/javascript">
    function init() {
        // Put your code here
    }
    window.onload = init();
</script>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜