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

前端 未结 5 1261
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:35

    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 tag:

    (function() {
    
        //statements...
    
    })();
    

提交回复
热议问题