javascript - RequireJS 是否异步加载文件?

标签 javascript node.js requirejs

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 调用?

最佳答案

这句话告诉你:

  1. 当 RequireJS 在 Node 中运行时,它可以在调用 requirejs(module_name) 时以真正同步的方式加载模块。 请注意,当 RequireJS 在浏览器中运行时,这没有等效项。是的,您可以在浏览器端执行 requirejs(module_name) 但这只有在模块运行时才不会出错已经被加载并且这个加载是异步发生的。它不是真正同步的。然而,在 Node 中运行时通过 RequireJS 完成的相同类型的调用是真正同步的。

  2. 但是,当您通过传递依赖项列表和回调来调用它时,回调将被异步调用。 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/

相关文章:

javascript - 如何使用javascript从数组中删除元素

node.js - MongoDB Atlas 触发器中的聚合不起作用

mysql - 如何在 nodejs/socket.io 中的客户端请求后对 mysql 数据库进行查询?

javascript - 1个按钮 2个功能

c# - 将 JS OnClientClick 添加到代码隐藏中的按钮时出现问题

javascript - 如何在不损失任何精度的情况下在 Node.js 中存储极大的数字?

backbone.js - Backbone EventAggregator 问题和问题

javascript - RequireJS:运行页面特定模块的最佳方法?

javascript - Require.js 不在浏览器中更新

javascript - Angular 中的全局保存按钮