8

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
  • nope. just waits then logs data as undefined. Commented Apr 29, 2014 at 14:19

3 Answers 3

11

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);
    });
}
Sign up to request clarification or add additional context in comments.

Comments

0

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'

Comments

-2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.