Survey on the resource available with RequireJS

So, I am writing an application using RequireJS and Socket.io, which checks if socket.io is available, and then, when connected, loads the application. In the case where socket.io is ever temporarily omitted, I would like the request to participate in the resource to be several times until it is available, and then continue to initialize the application.

Unfortunately (or maybe fortunately?), There seems to be some kind of caching mechanism requiring it to register scripts for scripts that don't load, so if you execute setTimeout in the error callback that the function returns socket, require will continue to throw errors even when the resource becomes available.

Is this an oversight or is there a reason to keep this error? More importantly, is there a workaround that would require relaying?

Here is an example of what I tried:

function initialize() { require(['socketio', function(io) { io.connect('http://localhost'); app._bootstrap(); }, function(err) { console.log(err); setTimeout(initialize, 10000); }); } 
+4
source share
1 answer

I know this is an old question, but for me it was intriguing, so I looked into it ...

There is a require.undef method that needs to be called to tell RequireJS not to cache the previous load failure status. See Also errbacks example.

Then you can simply request a callback with a null callback. The initial callback will still be called - there is no need for recursion. Something like that:

 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(); }); 
+6
source

Source: https://habr.com/ru/post/1490958/


All Articles