So I\'m writing an app using RequireJS and Socket.io that checks to see if the socket.io resource is available and then, on connection, bootstraps the app. In case socket.io
I know this is an old question, but it was intriguing to me so I looked into it...
There is a require.undef method you need to call in order to tell RequireJS not to cache the prior failure status of the load. See also errbacks example.
Then you can simply call require again with a null callback. The original callback will still be called -- no need for the recursion. Something like this:
function requireWithRetry(libname, cb, retryInterval, retryLimit) {
// defaults
retryInterval = retryInterval || 10000;
retryLimit = retryLimit || 10;
var retryCount = 0;
var retryOnError = function(err) {
var failedId = err.requireModules && err.requireModules[0];
if (retryCount < retryLimit && failedId === libname) {
// this is what tells RequireJS not to cache the previous failure status
require.undef(failedId);
retryCount++;
console.log('retry ' + retryCount + ' of ' + retryLimit)
setTimeout(function(){
// No actual callback here. The original callback will get invoked.
require([libname], null, retryOnError);
}, retryInterval);
} else {
console.log('gave up', err)
}
}
// initial require of the lib, using the supplied callback plus our custom
// error callback defined above
require([libname], cb, retryOnError);
}
requireWithRetry('socketio', function(io) {
io.connect('http://localhost');
app._bootstrap();
});