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

前端 未结 5 1263
Happy的楠姐
Happy的楠姐 2021-02-04 04:51

I\'m trying to fix an old script written for me. I need it to run without . I\'d like to run the function from inside the script wit

5条回答
  •  孤独总比滥情好
    2021-02-04 05:45

    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:

    
    

    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();
     });
    

提交回复
热议问题