jQuery document.ready()不能与Require.js一起使用

时间:2013-06-16 10:05:50

标签: javascript jquery requirejs document-ready domready

我在关闭正文标记之前调用Require.js:

    <script data-main="assets/scripts/src/main.js" src="assets/scripts/lib/requirejs/require.js"></script>
</body>

以下是我的main.js包含的内容:

requirejs.config({
    urlArgs: "bust=" + (new Date()).getTime(), // override browser cache
});

require(['views/appView'], function (App) {
    App.initialize(); // this is just to test the module is actually loading
});

appView.js包含:

define([
    'modernizr',
    'jquery',
    'underscore',
    'backbone',
    'common', // this module has about 4 other dependencies too
    'dust',
    'routers/main',
    'views/main'
], function (Modernizr, $, _, Backbone, Common, dust, router, mainView) {
    // This is supposed to load, even if jQuery loads after the DOM ready event
    $(document).on('ready', function () {
        console.log("I don't want to play nice");
    });

    return {
        initialize: function () {
            console.log("Init");
        }
    }
});

不幸的是,console.log("I don't want to play nice");根本不会发生

这是我的网络时间轴在Chrome开发者工具中的外观。正如您所看到的,DOM ready事件在jQuery加载之前触发 - 但是AFAIK,jQuery知道如何处理它!所以我迷路了。 enter image description here

2 个答案:

答案 0 :(得分:7)

应该是,

$(document).ready(function () {
    console.log("I don't want to play nice");
});

$(document).on("ready", handler),自jQuery 1.8起已弃用 http://api.jquery.com/ready/

答案 1 :(得分:2)

鉴于RequireJS仅用于加载特定页面所需的模块,开发人员可能不希望在某些页面上仅为其$(document).ready(function(){})回调加载整个jQuery库。或者,在appView.js中使用RequireJS'domReady

define([
    'domReady',
    'modernizr',
    'etc'
], function (domReady, Modernizr, etc) {
    domReady(function () {
        console.log("I'll play nice");
    });
});

或在!定义中添加domReady以避免嵌套回调:

define([
    'domReady!',
    'modernizr',
    'etc'
], function (domReady, Modernizr, etc) {
    console.log("I'll also play nice");
});