What are the difference between $(document).bind('ready', function) and $(document).ready(function() {})

[亡魂溺海] 提交于 2019-12-12 12:33:15

问题


I want to upgrade from requirejs version 2.0.0 to 2.1.5

Here is the code:

define(['jquery', 'test.js'],
    function ($, test) {
    var test = new $.test({
        //options
    });
    ....
});

test.js

(function($) {
    var registerEvents = function() {
        //dosth
    };
    $.test = function(options) {
        $(document).bind('ready', function() {
            registerEvents();
        });
        ...
        return test;
    }

    ...
});

In version 2.0.0, requirejs holds the dom ready event till all resources are downloaded, so it worked correctly https://github.com/jrburke/requirejs/issues/249

When I upgrade to requirejs version 2.1.5, the registerEvents function will never be called.

But supprisingly, if I change:

$(document).bind('ready', function() {
    registerEvents();
});

To:

$(document).ready(function() {
    registerEvents();
});

It worked fine

So my question is: What are the difference between them?

Edit: I am using jQuery v1.7.2

$(document).on('ready', function(){}) not working


回答1:


The difference is, as the docs say

There is also $(document).on( "ready", handler ), deprecated as of jQuery 1.8. This behaves similarly to the ready method but if the ready event has already fired and you try to .on( "ready" ) the bound handler will not be executed. Ready handlers bound this way are executed after any bound by the other three methods above. [em mine]

.bind and .on behave similarly.


This is the only difference between

$( document ).ready( handler )
$().ready( handler ) // (this is not recommended)
$( handler )

and

$( document ).on( "ready", handler )
$( document ).bind( "ready", handler )

that's mentioned in the docs, so I'm guessing is the most likely source of your issue



来源:https://stackoverflow.com/questions/27718996/what-are-the-difference-between-document-bindready-function-and-docume

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!