Saturday, November 20, 2010

Dynamically loading new script into page using jQuery

We mostly load external script files in our page using script src tag. But now and then, we need to load JavaScript file under script control. There are couple of use cases for this:


  • We don't to load file at runtime (because of some restriction, or because of file size);
  • or maybe we need to execute some condition before decide which file we will load.
jQuery provide <b>$.getScript()</b> utility function to enable this functionality. This function uses jQuery Ajax functions to fetch this file. 

Ok, let's see how it works!


Following code represent external JavaScript file (named: new_script.js).
$('#console').html("Script is loaded...");
function dragonBallFunction(value) {
    alert(value);
}

On page we have defined two buttons. First button load script file, second execute function from external file that first loaded.

As you can see it is quite simple:

$(function() {
    $('#loadButton').click(function() {
        $.getScript("new_script.js");
    });
    $("#executeButton").click(function() {
        dragonBallFunction('Piccolo is not saiyan!\n::Goku:: is!');
    });
});

//normal html stuff 


No comments:

Post a Comment