require.js同步加载 [英] require.js synchronous loading
问题描述
我想定义一个模块,该模块计算新的依赖关系,获取它,然后返回结果.像这样:
I'd like to define a module which computes a new dependancy, fetches it and then returns the result. Like so:
define(['defaults', 'get_config_name'], function(defaults, get_config_name) {
var name = get_config_name();
var config;
require.synchronous([configs / '+name'], function(a) {
config = defaults.extend(a);
});
return config;
});
是否有解决此问题的方法或更好的方法?
Is there a way to do this or a better way to attack this problem?
推荐答案
-
您可以尝试使用同步RequireJS调用
require('configs/'+get_config_name())
,但它将加载仅在已已加载的模块中同步该模块,否则它将引发异常.从技术上讲,同步加载模块/JavaScript文件是不可能的.UPD: 有可能(请参见Henrique的回答),但不建议这样做.它阻止JavaScript执行,从而导致整个页面冻结.因此,RequireJS不支持它.You may try to use synchronous RequireJS call
require('configs/'+get_config_name())
, but it will load a module synchronously only if it is already loaded, otherwise it will throw an exception.Loading module/JavaScript file synchronously is technically impossible.UPD: It's possible (see Henrique's answer) but highly unrecommended. It blocks JavaScript execution that causes to freezing of the entire page. So, RequireJS doesn't support it.从您的用例来看,您似乎不需要同步的RequireJS,您需要异步返回结果. AMD 模式允许定义依赖项并异步加载它们,但是模块的工厂功能必须同步返回结果.解决方案可能是使用 loader插件(在此处和
From your use case it seems that you don't need synchronous RequireJS, you need to return result asynchronously. AMD pattern allows to define dependencies and load them asynchronously, but module's factory function must return result synchronously. The solution may be in using loader plugin (details here and here):
// config_loader.js define(['defaults', 'get_config_name'], function(defaults, get_config_name) { return { load: function (resourceId, require, load) { var config_name = 'configs/' + get_config_name(); require([config_name], function(config) { load(defaults.extend(config)); }) } } }); // application.js define(['config_loader!'], function(config) { // code using config });
-
如果
get_config_name()
包含简单的逻辑并且不依赖于其他模块,则动态地进行计算会变得更好,更简单地图配置选项. If
get_config_name()
contains simple logic and doesn't depend on another modules, the better and simpler is calculating on the fly paths configuration option, or in case your config depends on context - map configuration option.function get_config_name() { // do something } require.config({ paths: { 'config': 'configs/' + get_config_name() } }); require(['application', 'defaults', 'config'], function(application, defaults, config) { config = defaults.extend(config); application.start(config); });
这篇关于require.js同步加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!