jQuery: usare $.getScript(): un esempio pratico

Questa funzione AJAX di jQuery serve ad importare codice JavaScript esterno nello scope corrente.

A titolo di esempio creiamo uno script come il seguente che chiameremo script.js:


"use strict";

if( typeof sum !== "function" ) {
    function sum() {
        var total = 0;
        if( arguments.length > 0 ) {
            for( var i = 0; i < arguments.length; i++ ) {
                var n = Number( arguments[i] );
                if( !isNaN( n ) ) {
                    total += n;
                }    
            }
        }
        return total;
    }
}

Quindi usiamo $.getScript() in questo modo:


"use strict";

$(function() {
    $.getScript( "script.js", function() {
        if( typeof sum === "function" ) {
            console.log( sum( 1, 2, 3 ) ); // 6
        }
    });
});

In pratica questa funzione usa AJAX per importare del codice JavaScript esterno nello scope della funzione usata come callback. Può essere usata anche per caricare plugin jQuery in modo asincrono.