Requ.js lazy loading remote URL

I have a file called moment.js on the local file system and upload it like this: require.js works:

initialize: function() { require(['moment'], function(data) { console.log(data); }); } 

However, if I do this:

 initialize: function() { require(['http://momentjs.com/downloads/moment.min.js'], function(data) { console.log(data); }); } 

data is returned undefined. Why is this? and how can I dynamically enable remote modules at runtime?

+7
javascript requirejs
source share
3 answers

I noticed that the code you are trying to load hardcodes is the name of the module as moment , so configure RequireJS in place 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); }); } 
+7
source share

I think that the URL for the moment should be without a file name extension, i.e. it should look like this: moment: ' http://momentjs.com/downloads/moment.min '

0
source share

If you need to load a module both locally and from a remote URL, you must name the module, if defined , and add the module "alias", which is called as a 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 the blog post. I wrote here .

-2
source share

All Articles