Making requirejs wait until files have loaded before continuing

11,217

Solution 1

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.

Solution 2

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');
}
Share:
11,217
Decrypter
Author by

Decrypter

I have a strong passion for programming and a particular interest in web technologies. I love to experiment with interesting web technologies both server and client side.

Updated on August 21, 2022

Comments

  • Decrypter
    Decrypter over 1 year

    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