Require.js lazy loading remote url

余生长醉 提交于 2019-12-22 05:01:30

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!