Add event handler for body.onload by javascript within <body> part

后端 未结 5 828
深忆病人
深忆病人 2020-12-13 18:10

We want to include a maps from Google Maps API in our document. The documentation tells to initialize the map with a function called by the onload() event of the body.

相关标签:
5条回答
  • 2020-12-13 18:26
    body.addEventListener("load", init(), false);
    

    That init() is saying run this function now and assign whatever it returns to the load event.

    What you want is to assign the reference to the function, not the result. So you need to drop the ().

    body.addEventListener("load", init, false);
    

    Also you should be using window.onload and not body.onload

    addEventListener is supported in most browsers except IE 8.

    0 讨论(0)
  • 2020-12-13 18:29

    Simply wrap the code you want to execute into the onload event of the window object:

    window.onload = function(){ 
       // your code here
    }
    
    0 讨论(0)
  • 2020-12-13 18:49

    You should really use the following instead (works in all newer browsers):

    window.addEventListener('DOMContentLoaded', init, false);
    
    0 讨论(0)
  • 2020-12-13 18:51

    As we were already using jQuery for a graphical eye-candy feature we ended up using this. A code like

    $(document).ready(function() {
        // any code goes here
        init();
    });
    

    did everything we wanted and cares about browser incompatibilities at its own.

    0 讨论(0)
  • 2020-12-13 18:53

    As @epascarello mentioned for W3C standard browsers, you should use:

    body.addEventListener("load", init, false);
    

    However, if you want it to work on IE<9 as well you can use:

    var prefix = window.addEventListener ? "" : "on";
    var eventName = window.addEventListener ? "addEventListener" : "attachEvent";
    document.body[eventName](prefix + "load", init, false);
    

    Or if you want it in a single line:

    document.body[window.addEventListener ? 'addEventListener' : 'attachEvent'](
        window.addEventListener ? "load" : "onload", init, false);
    

    Note: here I get a straight reference to the body element via the document, saving the need for the first line.

    Also, if you're using jQuery, and you want to use the DOM ready event rather than when the body loads, the answer can be even shorter...

    $(init);
    
    0 讨论(0)
提交回复
热议问题