Search code examples
jquerygoogle-chromegreasemonkeypreloaderuserscripts

Why does this reach main() yet jQuery is still undefined?


I'm trying to modify the various loaders out there so multiple scripts can be handled before the main function is called. This should load jQuery, then jQueryUI, and then call main() to actually start the userscript. However, it does loop through, but when it gets to main(), I get a console error from Chrome about jQuery being undefined.

!function loader (i) {
        var requires = [ 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js'
                       , 'https://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js'
                       ];
        var loadScript = function (i) {
                    var script    = document.createElement('script');
                    script.type   = 'text/javascript';
                    script.src    = requires[i];
                    script.onload = (++i === requires.length) ? function () { loader(i); }
                                                              : function () { main(); }
                    document.head.appendChild(script);
            };

        loadScript(i || 0);
}();

function main () {
    console.log(jQuery.version);
    console.log(jQuery.ui.version);
}

Solution

  • Here's the final script I came up with, if anyone's looking for this type of thing. http://userscripts.org/scripts/review/123588

    Pilate caught part of it, with the ternary. Nate B also had part of it, with jQuery using jQuery.fn.jquery (but UI being inconsistent and using jQuery.ui.version).

    It'd have been nice to figure out how to skip the wrapper bit in the middle, for 3rd party, but this works. :)