rikAtee rikAtee - 6 months ago 28
Javascript Question

requirejs race condition - how to block until previous file retrieved

common_tempaltes
file is not a requirejs file - rather a file that defines a global variable.

common_templates
needs
hogan
. they both are requested more or less at the same time, but race condition is in affect.
common_templates
sometimes wins so the code fails with "hogan not loaded yet".

require(['module1', 'hogan', 'common_templates'], function(Module){
Module.do_stuff() // this module also requires hogan and common_templates to be loaded
});


other than nested require, is there a built in way to tell require to block until
hogan
is fully downloaded?

nested:

require(['hogan'], function(Fn, Ui){
require(['common_templates'], function(){
require(['module1'], function(Module){
Module.do_stuff();
});
});
});


This approach seems a bit hacky. is there a built in way to work around these race conditions?

Answer

If common_templates is not an AMD module (doesn't contain a define([deps]) call), then you need to configure it as a shim:

require.config({
  shims: {
     common_templates: {
      deps: ["hogan"]
     }
  } 
});

Now, require(['module1', 'hogan', 'common_templates']) and require(['module1', 'common_templates']) should work.