0

In my code I am doing a require call inside a function. How to make a fresh request every time I make the function call?

function test(){
 require(['scriptpath'], function(App){
  console.log(App);
 });
}

test();
test();
test();
abs
  • 801
  • 6
  • 15
  • 1
    Does the script change for each call? Why is that if so? If so this may not be the solution, you may need to embed the script otherwise. – Mark Schultheiss Mar 25 '17 at 16:01
  • Explore this questions options perhaps: http://stackoverflow.com/questions/8315088/prevent-requirejs-from-caching-required-scripts – Mark Schultheiss Mar 25 '17 at 16:02
  • it is against all require() idea, but you can add cachebuster (like `+ '?=' + MATH.random()`) to your scriptpath and do such requsts. which probably will make memory leaks – zb' Mar 25 '17 at 16:03

1 Answers1

0

The problem you are facing is that RequireJS modules are singletons, and this is by design. Even if you play with urlArgs to add a parameter to bust the cache, you won't get the result you want. When you call test the first time, RequireJS does not have the module already loaded so it fetches it. Then when you call it again, it sees that scriptpath is already loaded and immediately calls the callback. See, it won't go into your configuration and look at urlArgs or paths or anything else. If the module is already loaded, that's the end of the story: the callback is called immediately.

You may be able to get the result you want by doing something similar to cache busting. I've been able to cause RequireJS to load the "same" module by doing something like this:

var times = 0;
function test() {
  times++;
  require(["foo.js?" + times], function () {
    console.log("got foo");
  });
}

The code above uses a different module name for each require call, and thus RequireJS will issue a new request for each require call.

You cannot just use Date.now() to tack on at the end of the module name because two calls to test() may get the same value from Date.now() because they happen faster than the resolution of the timer and this will result in a single network query. That's why I use the variable times instead.

Louis
  • 146,715
  • 28
  • 274
  • 320