问题
I have a file called moment.js on my local file system and loading it as follows with require.js works:
initialize: function() {
require(['moment'], function(data) {
console.log(data);
});
}
However, if I do:
initialize: function() {
require(['http://momentjs.com/downloads/moment.min.js'], function(data) {
console.log(data);
});
}
data comes back undefined. Why is this? and how do I dynamically include remote modules at runtime?
回答1:
I noticed that the code you are trying to load hardcodes the module name as moment so configure RequireJS on the spot so that you can require with the same name:
initialize: function() {
require.config({
paths: { moment: 'http://momentjs.com/downloads/moment.min' }
});
require(['moment'], function(data) {
console.log(data);
});
}
回答2:
I think url for moment should be without filename extension i.e. it should look like as follows: moment:'http://momentjs.com/downloads/moment.min'
回答3:
If you need to load a module both locally AND from a remote URL, you should name the module when defining it and add an "alias" module which is named like the URL, with both modules defined inside the same file.
Example:
//define a module NAMED "moment" using the first optional name paramter
define("moment", ["require"], function (require) {
/*module code goes here*/
});
//alias module to use when lazy loading from URL
define("http://momentjs.com/downloads/moment.min.js", ["require"], function (require) {
return require("moment");//returns original module
});
You can read more about this in a blog post I wrote here.
来源:https://stackoverflow.com/questions/23365972/require-js-lazy-loading-remote-url