Thursday, October 10, 2013

Dynamically load a Javascript file with jQuery


jQuery's $.getScript() function is a shorthand wrapper to $.ajax() which easily allows remote Javascript to be loaded into the current page.

Using $.getScript():

Method : 1



$.getScript('/javascript/myscript.js');


Method :2


$.getScript('/javascript/myscript.js', function() {

    // do something here

});

Note that this makes a GET request and if POST is required then you need to use the $.ajax() function directly, as shown below, instead of the $.getScript() shorthand.

Using $.ajax() instead:

The same thing can be done using the $.ajax function which allows for some more control over the parameters, such as making it a POST request instead or ensuring the file is never cached.

Method :1

$.ajax({

    url: '/javascript/myscript.js',

    dataType: 'script'

});

Method : 2
on_js_load_complete() {
    // do something
}


$.ajax({

    url : '/javascript/myscript.js',

    success: on_js_load_complete()

});

Load multiple script in best way:
$.when(
    $.getScript( "/mypath/myscript1.js" ),
    $.getScript( "/mypath/myscript2.js" ),
    $.getScript( "/mypath/myscript3.js" ),
    $.Deferred(function( deferred ){
        $( deferred.resolve );
    })
).done(function(){

    //place your code here, the scripts are all loaded

});

Above techniques are mostly use in jquery to load specific module of javascript and jquery.


1 comment: