When is RequireJS' require call asynchronous? When is it synchronous?

折月煮酒 提交于 2019-11-30 14:03:51

RequireJS always loads modules asynchronously but it allow a form of require that looks synchronous. Your second snippet is actually missing some really important code. (Also, the module name for jQuery is hardcoded to jquery. You could write a configuration that allows you to refer to it as jQuery but there's no point.) This form of the require calls is designed to be used inside modules so:

define(function (require) {
    var $ = require("jquery");
    $.doSomething();
});

What RequireJS does with the code above is transform it into this before executing it:

define(['jquery'], function (require) {
    var $ = require("jquery");
    $.doSomething();
});

Note the addition of the dependency as the first argument of define. When RequireJS executes the code, it finds the dependency, loads jquery and then calls the anonymous function. By the time require("jquery") is encountered the module is already loaded. At the end of the day while the require call looks synchronous, the loading of the module it requires still happens asynchronously.

Can you use this synchronous form require outside of a define call? Only if you are okay with failures. This require call will fail if the module passed to it is not already loaded. You get the infamous error:

Module name ... has not been loaded yet for context: ...

Using it in a define like I've shown above is safe. Or I guess you could do:

require(['jquery'], function (require) {
    var $ = require("jquery");
    $.doSomething();
});

which would work but what's the point of manually repeating the dependency. (In case you wonder, RequireJS does not transform a require call with a callback like the one I have in my example here in the same way it transforms a define call as I've shown above.)

According to require.js docs it is a wrapper. So it is rebuilding code to work asynchronously. It is called CommonJs wrapper. You can find more info about it here

I don't know requirejs. But I think it's possible to load module in both sync and async ways.

function require(name,cb){
    if(cb !== undefined){
        requireAsync(name,cb);
    }else{
        requireSync(name);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!