[英]jQuery document.ready() doesn't work with Require.js
I am calling Require.js from right before the closing body tag: 我在关闭body标签之前从Require.js调用:
<script data-main="assets/scripts/src/main.js" src="assets/scripts/lib/requirejs/require.js"></script>
</body>
Here is what my main.js
contains: 这是我的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
});
And appView.js contains: 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");
}
}
});
Unfortunately, this: console.log("I don't want to play nice");
不幸的是,这是: console.log("I don't want to play nice");
does not happen at all . 根本不会发生。
This is how my network timeline looks in Chrome Dev Tools. 这就是我的网络时间表在Chrome Dev Tools中的外观。 As you can see, the DOM ready event fires way before jQuery loads - but AFAIK, jQuery knows how to handle this! 如您所见,DOM就绪事件在jQuery加载之前触发-但是AFAIK,jQuery知道如何处理! So I am lost. 所以我迷路了。
It should be, 它应该是,
$(document).ready(function () {
console.log("I don't want to play nice");
});
$(document).on("ready", handler)
, deprecated as of jQuery 1.8 http://api.jquery.com/ready/ $(document).on("ready", handler)
,从jQuery 1.8开始不推荐使用 http://api.jquery.com/ready/
Given that RequireJS is used to load only the modules needed for a specific page, developers may not want to load the entire jQuery library on some pages just for its $(document).ready(function(){})
callback. 鉴于RequireJS仅用于加载特定页面所需的模块,开发人员可能不希望仅出于其$(document).ready(function(){})
回调而在某些页面上加载整个jQuery库。 Alternatively, use RequireJS' domReady in appView.js: 另外,使用RequireJS” domready中在appView.js:
define([
'domReady',
'modernizr',
'etc'
], function (domReady, Modernizr, etc) {
domReady(function () {
console.log("I'll play nice");
});
});
or add an !
或添加一个!
on the domReady
define to avoid nested callbacks: 在domReady
定义以避免嵌套回调:
define([
'domReady!',
'modernizr',
'etc'
], function (domReady, Modernizr, etc) {
console.log("I'll also play nice");
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.