kubetail-org / loadjs

A tiny async loader / dependency manager for modern browsers (899 bytes)
MIT License
2.58k stars 150 forks source link

Confused by "Uncaught LoadJS" error #44

Closed dpantel closed 7 years ago

dpantel commented 7 years ago

Hello. Forgive me if I am missing something obvious. I am a JS novice...

loadjs('BROKEN-URL-TO-CDN/lib.js', 'bundle', {
    before: function(path, el) {
        //add SRI and crossorigin
        el.integrity = 'xxxx';
        el.crossOrigin = 'anonymous';
    },
    error: function(pathsNotFound) {
        //fallback to local copy
        loadjs('js/lib.js', 'bundle');
    }
});

I am trying to load a file from a CDN and fall back to a local copy on error. When testing the fallback, I purposefully corrupted the URL of the CDN, expecting loadJS to load the local file. However, what I got instead was this:

GET broken-url-to-cdn/lib.js::ERR_NAME_NOT_RESOLVED
    t @ loadjs.min.js:1
    r @ loadjs.min.js:1
    i @ loadjs.min.js:1
    (anonymous) @ (index):53
loadjs.min.js:1 Uncaught LoadJS
    i @ loadjs.min.js:1
    error @ (index):61
    (anonymous) @ loadjs.min.js:1
    i @ loadjs.min.js:1
    s.onload.s.onerror.s.onbeforeload @ loadjs.min.js:1

Please help me understand what is going on (and how to fix it). Thanks.

amorey commented 7 years ago

The first error looks like a domain name resolution error. The second error is thrown by LoadJS when you re-use a bundle name ("bundle" in this case).

To avoid the bundle name error you can use the loadjs.reset() method to reset all the bundles or loadjs.done() method to control when the bundle gets defined:

loadjs('BROKEN-URL-TO-CDN/lib.js', {
    before: function(path, el) {
        //add SRI and crossorigin
        el.integrity = 'xxxx';
        el.crossOrigin = 'anonymous';
    },
    success: function() {
        loadjs.done('bundle');
    },
    error: function(pathsNotFound) {
        //fallback to local copy
        loadjs('js/lib.js', {success: function() {loadjs.done('bundle');}});
    }
});
dpantel commented 7 years ago

Works like a charm. And now I also have a better understanding of what done() does (was not very clear from the docs).

Thank you!

amorey commented 7 years ago

Great! Happy to hear it worked and thanks for the feedback!