1

我在结束 body 标记之前调用 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 就绪事件在 jQuery 加载之前触发 - 但 AFAIK,jQuery 知道如何处理这个!所以我迷路了。 在此处输入图像描述

4

2 回答 2

6

它应该是,

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

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

于 2013-06-16T10:15:43.540 回答
2

鉴于 RequireJS 仅用于加载特定页面所需的模块,开发人员可能不想在某些页面上加载整个 jQuery 库只是为了它的$(document).ready(function(){})回调。或者,在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");
});
于 2014-02-04T18:55:14.667 回答