Javascript load vs ready vs domready vs DOMContentLoaded events

前端 未结 4 1369
余生分开走
余生分开走 2021-02-01 19:01

I am a bit lost in the \"start up\" events - there are so many different events and are named differently in the DOM and in various frameworks like jQuery. What are all

相关标签:
4条回答
  • 2021-02-01 19:37

    .ready()

    While JavaScript provides the load event for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received. In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed. The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers and run other jQuery code. When using scripts that rely on the value of CSS style properties, it's important to reference external stylesheets or embed style elements before referencing the scripts.

    In cases where code relies on loaded assets (for example, if the dimensions of an image are required), the code should be placed in a handler for the load event instead.

    The .ready() method is generally incompatible with the attribute. If load must be used, either do not use .ready() or use jQuery's .load() method to attach load event handlers to the window or to more specific items, like images.

    Ref: http://api.jquery.com/ready/

    .load()

    This method is a shortcut for .on( "load", handler ).

    The load event is sent to an element when it and all sub-elements have been completely loaded. This event can be sent to any element associated with a URL: images, scripts, frames, iframes, and the window object.

    In general, it is not necessary to wait for all images to be fully loaded. If code can be executed earlier, it is usually best to place it in a handler sent to the .ready() method.

    Ref: http://api.jquery.com/load-event/

    GlobalEventHandlers.onload

    The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images and sub-frames have finished loading.

    There are also Gecko-Specific DOM Events like DOMContentLoaded and DOMFrameContentLoaded (which can be handled using EventTarget.addEventListener()) which are fired after the DOM for the page has been constructed, but do not wait for other resources to finish loading.

    Cross-browser fallback

    Internet Explorer 8 supports the readystatechange event, which can be used to detect that the DOM is ready. In earlier version of Internet Explorer, this state can be detected by regularily trying to execute document.documentElement.doScroll("left");, as this snippet will throw an error until the DOM is ready.

    General-purpose JS libraries such as jQuery offer cross-browser methods to detect that the DOM is ready. There are also standalone scripts that offer this feature : contentloaded.js (supports only one listener) and jquery.documentReady.js (doesn't depend on jQuery, despite its name). Ref: https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers.onload

    Code:

    document.addEventListener("DOMContentLoaded", function (event) {
        console.log("DOM fully loaded and parsed");
    });
    
    function load() {
        console.log("load event detected!");
    }
    window.onload = load;
    
    $(document).ready(function () {
        console.log('ready');
    });
    
    $(window).load(function () {
        console.log('loaded');
    });
    

    Timeline demo: http://jsfiddle.net/HgJ33/

    0 讨论(0)
  • 2021-02-01 19:47

    It is better to think from the perspective of what you want and which browsers to support.

    To make manipulations in Document Object Model (DOM) you will have to make sure the HTML page is loaded over network and parsed into a tree. One way of tackling this is by writing all code at end of the HTML file which leads to processing those javascript only after parsing the HTML. The other newer standard way is to listen for the DOMReady or DOMContentLoaded event or ready event to make sure the handler is run only after DOM is ready

    After DOM tree is built browser will request for images, audio, video etc. After all these resources are loaded window load event is fired ,now the page is ready to be rendered fully.

    So basically you should just think if your code can be executed with the DOM tree ready, or do you need everything loaded to run your code. If the native javascript implementation of DOM ready doesnt cover all the browsers you need to support, you can go for jQuery DOMready that is the reason why its made.

    0 讨论(0)
  • 2021-02-01 19:57

    Can be interesting to write down the different frameworks and their events:

    Here is test series using jsFiddle. Same html, different frameworks, difference in ms.

    Mootools

    window.onload = function () {
        var now = new Date().getTime() - time;
        console.log(now, 'onload')             // 14 ms
    };
    window.addEvent('load', function () {
        var now = new Date().getTime() - time;
        console.log(now, 'load')               // 15 ms
    });
    window.addEvent('domready', function () {
        var now = new Date().getTime() - time;
        console.log(now, 'domready')           // 1 ms
    });
    

    jQuery

    window.onload = function () {
        var now = new Date().getTime() - time;
        console.log(now, 'onload')             // 20 ms
    };
    $(document).on('DOMContentLoaded', function () {
        var now = new Date().getTime() - time;
        console.log(now, 'DOMContentLoaded')   // 10 ms
    });
    $(document).on('ready', function () {
        var now = new Date().getTime() - time;
        console.log(now, 'ready')              // 20 ms
    });
    

    Dojo Toolkit

    dojo.addOnLoad(function() {
        //do stuff
    });
    

    YUI

    YUI().use('*',function(Y) {
        Y.on("domready", function() {
            //do stuff
        }, Y, "The DOMContentLoaded event fired.  The DOM is now safe to modify via script.");
    });
    

    Prototype

    document.observe("dom:loaded", function() { 
        //do stuff
    });
    

    Sencha JS

    Ext.onReady(function() {
        //do stuff
    });
    
    0 讨论(0)
  • 2021-02-01 19:59

    In general, previosus answers are very good and full. But one important difference between .ready() and DOMContentLoaded event exists.

    Most browsers provide similar functionality in the form of a DOMContentLoaded event. However, jQuery's .ready() method differs in an important and useful way: If the DOM becomes ready and the browser fires DOMContentLoaded before the code calls .ready( handler ), the function handler will still be executed. In contrast, a DOMContentLoaded event listener added after the event fires is never executed.

    Ref. https://api.jquery.com/ready/

    As we see from this, .ready() is executed at least once in all cases.

    For example, in browser console we may define

    >> function sample()
    {
      console.log('This is sample.');
    
      $( document ).ready(function ()
      {
        console.log("Ready is working in all cases.")
      });  
    }
    undefined
    

    and in result we have

    >> sample();
    undefined
    This is sample. debugger eval code:3:11
    Ready is working in all cases. debugger eval code:7:13
    >> sample();
    undefined
    This is sample. debugger eval code:3:11
    Ready is working in all cases. debugger eval code:7:13
    
    0 讨论(0)
提交回复
热议问题