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();
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();
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.