我是RequireJS的新手,我一直坚持加载订单.
我有一个全局项目配置,我需要在位于js/app/*中的模块之前加载.
这是我的结构:
index.html
config.js
js/
require.js
app/
login.js
lib/
bootstrap-2.0.4.min.js
Run Code Online (Sandbox Code Playgroud)
这是config.js文件:
var Project = {
'server': {
'host': '127.0.0.1',
'port': 8080
},
'history': 10, // Number of query kept in the local storage history
'lang': 'en', // For future use
};
Run Code Online (Sandbox Code Playgroud)
这是我的requirejs文件(app.js):
requirejs.config({
//By default load any module IDs from js/lib
baseUrl: 'js/lib',
//except, if the module ID starts with "app",
//load it from the js/app directory. paths
//config is relative to the baseUrl, and
//never includes a ".js" extension since
//the paths config could be for a directory.
paths: {
bootstrap: '../lib/bootstrap-2.0.4.min',
app: '../app',
},
shim: {
'app': {
deps: ['../../config'],
exports: function (a) {
console.log ('loaded!');
console.log (a);
}
} // Skual Config
},
});
var modules = [];
modules.push('jquery');
modules.push('bootstrap');
modules.push('app/login');
// Start the main app logic.
requirejs(modules, function ($) {});
Run Code Online (Sandbox Code Playgroud)
但有时候,当我加载页面时,我有一个"项目"是未定义的,因为login.js已经被加载到config.js之前.
我怎样才能强制首先加载config.js,无论如何?
注意:我看到order.js作为RequireJS的插件,但是自从v2以来它显然不受支持,取而代之的是shim.
谢谢你的帮助!
tom*_*ors 26
今天遇到了类似的问题 - 我们想要确保在其他任何事情之前加载的引导数据,并且在评估任何其他模块之前设置暴露该数据的模块.
我发现强制加载顺序的最简单的解决方案是在继续应用初始化之前简单地要求加载模块:
require(["bootstrapped-data-setup", "some-other-init-code"], function(){
require(["main-app-initializer"]);
});
Run Code Online (Sandbox Code Playgroud)
fan*_*uka 20
有一种可能的解决方案来为要加载的模块构建队列.在这种情况下,所有模块将按照确切的顺序逐个加载:
var requireQueue = function(modules, callback) {
function load(queue, results) {
if (queue.length) {
require([queue.shift()], function(result) {
results.push(result);
load(queue, results);
});
} else {
callback.apply(null, results);
}
}
load(modules, []);
};
requireQueue([
'app',
'apps/home/initialize',
'apps/entities/initialize',
'apps/cti/initialize'
], function(App) {
App.start();
});
Run Code Online (Sandbox Code Playgroud)
eku*_*ela 15
如果将js文件定义为AMD模块,则无需担心加载顺序.(或者你可以使用shim配置,如果你不能修改config.js和login.js调用define).
config.js看起来像这样:
define({project: {
'server': {
'host': '127.0.0.1',
'port': 8080
},
'history': 10, // Number of query kept in the local storage history
'lang': 'en', // For future use
}});
Run Code Online (Sandbox Code Playgroud)
login.js:
define(['jquery', '../../config'], function($, config) {
// here, config will be loaded
console.log(config.project)
});
Run Code Online (Sandbox Code Playgroud)
同样,只有define()在模块内部调用不是一个选项时才应该使用shim config .
| 归档时间: |
|
| 查看次数: |
26894 次 |
| 最近记录: |