[removed] vs [removed]

后端 未结 9 1285

Which is more widely supported: window.onload or document.onload?

9条回答
  •  野的像风
    2020-11-21 06:09

    The general idea is that window.onload fires when the document's window is ready for presentation and document.onload fires when the DOM tree (built from the markup code within the document) is completed.

    Ideally, subscribing to DOM-tree events, allows offscreen-manipulations through Javascript, incurring almost no CPU load. Contrarily, window.onload can take a while to fire, when multiple external resources have yet to be requested, parsed and loaded.

    ►Test scenario:

    To observe the difference and how your browser of choice implements the aforementioned event handlers, simply insert the following code within your document's - - tag.

    
    

    ►Result:

    Here is the resulting behavior, observable for Chrome v20 (and probably most current browsers).

    • No document.onload event.
    • onload fires twice when declared inside the , once when declared inside the (where the event then acts as document.onload ).
    • counting and acting dependent on the state of the counter allows to emulate both event behaviors.
    • Alternatively declare the window.onload event handler within the confines of the HTML- element.

    ►Example Project:

    The code above is taken from this project's codebase (index.html and keyboarder.js).


    For a list of event handlers of the window object, please refer to the MDN documentation.

提交回复
热议问题