Alternative to <body onload=“init ();”>

2020-05-23 09:02发布

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 inside the script without inline code like that command. Sorry I'm not a JS expert but how do I do this?

标签: javascript
5条回答
我只想做你的唯一
2楼-- · 2020-05-23 09:17

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();
 });
查看更多
Bombasti
3楼-- · 2020-05-23 09:19
<script type="text/javascript">
    function init() {
        // Put your code here
    }
    window.onload = init;
</script>

Or, if you are using jQuery:

$(function() {
    // Your code here
});
查看更多
够拽才男人
4楼-- · 2020-05-23 09:20
<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>
查看更多
家丑人穷心不美
5楼-- · 2020-05-23 09:21

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...

})();
查看更多
Emotional °昔
6楼-- · 2020-05-23 09:41

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', ...).

查看更多
登录 后发表回答