我正在使用 requirejs 构建我的 Backbone 项目。一切正常,我能够使用优化器将所有 js 模块和模板编译到一个 main.js 文件中。问题是 main.js 大约有 1.5 兆。在工作中,这很好,因为我们的互联网连接速度很快,但我注意到在一些较慢的连接中,require.js 在 main.js 能够加载之前超时。
有没有什么办法可以避免我改变 waitSeconds 超时?
例如,有没有办法将 main.js 文件分解成多个部分,或者强制 require 等到加载 main.js 时产生错误?
最佳答案
我认为您不需要全部 1.5mb 来向用户显示初始应用程序。因此,您可以在代码中要求某些带有条件的部分。所以不是:
define(['module1','module2','module3','module4'], function(m1, m2, m3, m4){
if(m1.someCondition){
m2.start()
}else{
m3.start()
}
})
您可以使用 require
加载应用的部分内容:
define(['module1'], function(m1){
m1.start();
if(m1.someCondition){
var name = 'module2'
m2 = require(name)
m2.start()
}else{
var name = 'module3'
m3 = require(name)
m3.start()
}
})
请注意,只有当传递的名称不是字符串时,优化器才会忽略模块
From the docs:
The optimizer will only combine modules that are specified in arrays of string literals that are passed to top-level require and define calls, or the require('name') string literal calls in a simplified CommonJS wrapping. So, it will not find modules that are loaded via a variable name:
var mods = someCondition ? ['a', 'b'] : ['c', 'd'];
> require(mods);
关于javascript - 使用优化器在慢速连接上加载 main.js 时 RequireJS 超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12402684/