Javascript load vs ready vs domready vs DOMContentLoaded events

前端 未结 4 1406
余生分开走
余生分开走 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: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
    });
    

提交回复
热议问题