开发者

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

开发者 https://www.devze.com 2023-04-08 00:59 出处:网络
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

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

精彩评论

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