require.js synchronous loading

六月ゝ 毕业季﹏ 提交于 2019-12-17 19:08:28

问题


I'd like to define a module which computes a new dependancy, fetches it and then returns the result. Like so:

define(['defaults', 'get_config_name'], function(defaults, get_config_name) {
    var name = get_config_name();
    var config;
    require.synchronous([configs / '+name'], function(a) {
        config = defaults.extend(a);
    });
    return config;
});

Is there a way to do this or a better way to attack this problem?


回答1:


  • You may try to use synchronous RequireJS call require('configs/'+get_config_name()), but it will load a module synchronously only if it is already loaded, otherwise it will throw an exception. Loading module/JavaScript file synchronously is technically impossible. UPD: It's possible (see Henrique's answer) but highly unrecommended. It blocks JavaScript execution that causes to freezing of the entire page. So, RequireJS doesn't support it.

  • From your use case it seems that you don't need synchronous RequireJS, you need to return result asynchronously. AMD pattern allows to define dependencies and load them asynchronously, but module's factory function must return result synchronously. The solution may be in using loader plugin (details here and here):

    // config_loader.js
    define(['defaults', 'get_config_name'], function(defaults, get_config_name) {
        return {
            load: function (resourceId, require, load) {
                var config_name = 'configs/' + get_config_name();
                require([config_name], function(config) {
                    load(defaults.extend(config));
                })
            }
        }
    });
    
    // application.js
    define(['config_loader!'], function(config) {
        // code using config
    });
    
  • If get_config_name() contains simple logic and doesn't depend on another modules, the better and simpler is calculating on the fly paths configuration option, or in case your config depends on context - map configuration option.

    function get_config_name() {
        // do something
    }
    require.config({
        paths: {
            'config': 'configs/' + get_config_name()
        }
    });
    require(['application', 'defaults', 'config'], function(application, defaults, config) {
        config = defaults.extend(config);
        application.start(config);
    });
    



回答2:


Loading JavaScript synchronously is NOT technically impossible.

function loadJS(file){  
   var js = $.ajax({ type: "GET", url: file, async: false }).responseText; //No need to append  
}

console.log('Test is loading...');
loadJS('test.js');
console.log('Test was loaded:', window.loadedModule); //loadedModule come from test.js


来源:https://stackoverflow.com/questions/13225245/require-js-synchronous-loading

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