[removed] vs [removed]

后端 未结 9 1298

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

9条回答
  •  北恋
    北恋 (楼主)
    2020-11-21 06:14

    According to Parsing HTML documents - The end,

    1. The browser parses the HTML source and runs deferred scripts.

    2. A DOMContentLoaded is dispatched at the document when all the HTML has been parsed and have run. The event bubbles to the window.

    3. The browser loads resources (like images) that delay the load event.

    4. A load event is dispatched at the window.

    Therefore, the order of execution will be

    1. DOMContentLoaded event listeners of window in the capture phase
    2. DOMContentLoaded event listeners of document
    3. DOMContentLoaded event listeners of window in the bubble phase
    4. load event listeners (including onload event handler) of window

    A bubble load event listener (including onload event handler) in document should never be invoked. Only capture load listeners might be invoked, but due to the load of a sub-resource like a stylesheet, not due to the load of the document itself.

    window.addEventListener('DOMContentLoaded', function() {
      console.log('window - DOMContentLoaded - capture'); // 1st
    }, true);
    document.addEventListener('DOMContentLoaded', function() {
      console.log('document - DOMContentLoaded - capture'); // 2nd
    }, true);
    document.addEventListener('DOMContentLoaded', function() {
      console.log('document - DOMContentLoaded - bubble'); // 2nd
    });
    window.addEventListener('DOMContentLoaded', function() {
      console.log('window - DOMContentLoaded - bubble'); // 3rd
    });
    
    window.addEventListener('load', function() {
      console.log('window - load - capture'); // 4th
    }, true);
    document.addEventListener('load', function(e) {
      /* Filter out load events not related to the document */
      if(['style','script'].indexOf(e.target.tagName.toLowerCase()) < 0)
        console.log('document - load - capture'); // DOES NOT HAPPEN
    }, true);
    document.addEventListener('load', function() {
      console.log('document - load - bubble'); // DOES NOT HAPPEN
    });
    window.addEventListener('load', function() {
      console.log('window - load - bubble'); // 4th
    });
    
    window.onload = function() {
      console.log('window - onload'); // 4th
    };
    document.onload = function() {
      console.log('document - onload'); // DOES NOT HAPPEN
    };

提交回复
热议问题