Search code examples
jqueryjquery-deferredgetscript

jQuery getScript() not resolving


I am using jQuery's getScript() to load separate javascript files. The files seem to load fine (I know this as when I put an incorrect URL, it throws an error - no error with the correct URL).

However, the done()function does not seem to work. The console does not log 'done', nor do any of the functions get called.

(function($) {
    $.when(
        $.getScript( templateUrl + "/assets/js/variables.js" ),
        $.getScript( templateUrl + "/assets/js/functions.js" ),
        $.getScript( templateUrl + "/assets/js/events.js" ),
        $.Deferred(function( deferred ){
            $( deferred.resolve );
        })
    ).done(function(){

        console.log("done");

        swapBackgroundImgs();
        singleLarge();
        bindFlexorder();
        bindSvgeezy();
        bindPlaceholder();
        preloadImages();

    });
})( jQuery );

Solution

  • The done callback is never triggered because you've explicitly created a Deferred and never resolved it. $.when waits for all of the promises to be resolved.

    The code you have in your $.Deferred:

    $( deferred.resolve );
    

    ...will schedule the Deferred's resolve function as a ready callback, but the function will get called with the wrong this (document rather than the Deferred object; more: Mythical methods), which probably makes it throw an error ready buries.

    Simply remove that $.Deferred entirely, or if your goal is to wait for ready, make sure this gets set correctly when calling resolve:

    $.Deferred(deferred) {
        $(function() {
            deferred.resolve();
        });
    })
    

    or:

    $.Deferred(deferred) {
        $($.proxy(deferred.resolve, deferred));
    })
    

    or, but note the comment:

    $.Deferred(deferred) {
        // Deprecated in jQuery 1.8
        $(document).on("ready", deferred, "resolve");
    })