javascript 让 requirejs 等到文件加载完毕再继续
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16925047/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Making requirejs wait until files have loaded before continuing
提问by Decrypter
Is there a way to block javascript until requirejs has loaded the files?
有没有办法在 requirejs 加载文件之前阻止 javascript?
I thought doing the following would work because I don't have a callback.
我认为执行以下操作会有效,因为我没有回调。
var requireFile = require(['example']);
but it is still asynchronous.
但它仍然是异步的。
If I do have a callback specified is there a way to block until example is loaded, then execute the callback.
如果我确实指定了回调,是否有办法阻止直到加载示例,然后执行回调。
For example.
例如。
require(['example'], function(){
console.log('hello');
});
console.log('world');
Console should therefore be:
因此,控制台应该是:
-hello
-你好
-world
-世界
I am seeing
我在看
-world
-世界
-hello
-你好
采纳答案by Lee Meador
You can't block until it returns. But you usually don't have to.
在它返回之前你不能阻止。但您通常不必这样做。
You probably have some code that depends on the return from 'require', that code needs to go in the callback (or get called from inside the callback)
您可能有一些依赖于“require”返回的代码,该代码需要进入回调(或从回调内部调用)
It can be a problem when you already have a bunch of code but its the only way to do it.
当您已经有一堆代码但这是唯一的方法时,这可能是一个问题。
Sometimes you can have the other code not run until it sees that something it needs has loaded.
有时您可以让其他代码不运行,直到它看到它需要的东西已经加载。
Sometimes you can just skip it running and it will get invoked later. Sometimes you have to set up a timer that keeps looking for that 'something' and then pausing a bit if not.
有时你可以跳过它运行,它会在稍后被调用。有时您必须设置一个计时器来不断寻找“某物”,如果没有则暂停一下。
回答by Lyn Headley
You can wrap the code you want to delay in a function, then call that function from the require callback.
您可以将要延迟的代码包装在一个函数中,然后从 require 回调中调用该函数。
require(['example'], function(){
console.log('hello');
world();
});
function world() {
console.log('world');
}