Note: requirejs([], function() {}) will call the function callback asynchronously in RequireJS 2.1+ (for earlier versions it was synchronously called). However, when running in Node, module loading will be loaded using sync IO calls, and loader plugins should resolve calls to their load method synchronously. This allows sync uses of the requirejs module in node to work via requirejs('stringValue') calls:
这是什么意思?这是否意味着 node 中的 requirejs 不是真正的异步加载文件?因为它使用同步 IO 调用?
最佳答案
这句话告诉你:
当 RequireJS 在 Node 中运行时,它可以在调用
requirejs(module_name)
时以真正同步的方式加载模块。 请注意,当 RequireJS 在浏览器中运行时,这没有等效项。是的,您可以在浏览器端执行requirejs(module_name)
但这只有在模块运行时才不会出错已经被加载并且这个加载是异步发生的。它不是真正同步的。然而,在 Node 中运行时通过 RequireJS 完成的相同类型的调用是真正同步的。但是,当您通过传递依赖项列表和回调来调用它时,回调将被异步调用。
requirejs([], function() {})
形式的调用在浏览器和 Node 中都是异步的。
在评论中你问:
I'm a bit confused, if it's synchronously loading anyway, why not just use
requirejs('foo')
?
如果此调用仅在 Node 中运行,那么您不必费心使用调用的异步形式。但是,如果您编写的代码应该在 Node、 和 浏览器中运行,您必须小心使用此类调用的方式。例如一个 main.js
文件:
requirejs.config({...})
var foo = requirejs('foo');
foo.whatever();
最多只能在浏览器中间歇性地失败。至少偶尔,它会提高 "module not yet loaded for context" error .如果您希望代码无错误地运行,您必须执行以下操作:
requirejs.config({...})
requirejs('foo', function (foo) {
foo.whatever();
});
关于javascript - RequireJS 是否异步加载文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31558867/