Decrypter
Decrypter

Reputation: 3000

Making requirejs wait until files have loaded before continuing

Is there a way to block javascript until requirejs has loaded the files?

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

Upvotes: 4

Views: 12294

Answers (2)

Lyn Headley
Lyn Headley

Reputation: 11588

You can wrap the code you want to delay in a function, then call that function from the require callback.

require(['example'], function(){
    console.log('hello');
    world();
});

function world() {
  console.log('world');
}

Upvotes: 6

Lee Meador
Lee Meador

Reputation: 12985

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)

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.

Upvotes: 1

Related Questions