Thursday, June 06, 2013

Dynamic Script Loading using jQuery


We have already seen how dynamic Javascript can be inserted to the HTML document using Javascript in my previous article. Here we would see how we can get the same task done using jQuery getScript() method. This function actually loads a script from the SERVER using ajax method and then executes it. It has the following syntax :

jQuery.getScript( URL_for_script, load_success_callback( data, status, xhr ) );

The 2nd argument is optional. We can use .fail() and .done() methods with it as failure and success callbacks respectively. Let's write a small program which loads a script which is a function.

<script src='js/jquery-latest.js'></script>

<script>
// Define a variable in global scope
var click_times = 1;

// Load scripts dynamically
function load_script()
{
  jQuery.getScript("js/test.js")
 
  // SUCCESS callback
  .done(function(){
    jQuery("#status_div").html('Script Loaded');
  })
 
  // FAIL callback
  .fail(function(){
    jQuery("#status_div").html('Script Failed');
  });

}
</script>

<input type='button' value='Load Script' onclick='load_script()'>
<input type='button' value='This does not work' id='inactive_button'>
<div id='status_div'></div>


We have 2 buttons -- 'Load Script' and 'This does not work' and a DIV with id 'status_div'.


The 'This does not work' button remains inactive initially. Now when we click the 'Load Script' button, it loads a test.js file whose contents is given below ::

// Add a click event to the inactive button
jQuery('#inactive_button').on('click', function(){

// It can access global Variable also
if( click_times == 1)
 {
   // Change BUTTON TEXT only once
   jQuery(this).val('This Now WORKS !!');
 }

// Alert
alert('This button is now active, Clicked : ' + click_times + ' times');

// Increase number of click value
click_times++;

});


We used jQuery on() method to attach a "click" event to the button. So, every time the button is clicked, it alerts the message mentioning total number of clicks it got so far. Below is the screenshot :




The done() method attached to getScript() updates the DIV 'status_div' with status message. It can be done away with in below shown method ::

jQuery.getScript("js/test.js", function(data){
 
    // SUCCESS callback
    jQuery("#status_div").html('Script Loaded:' + data);
  })
 
   // FAIL callback
  .fail(function(){
    jQuery("#status_div").html('Script Failed');
  });


This code does the same stuff; however it also inserts the text received in ajax response in the div.

The only problem with the above code is that, it repeatedly attach events to the button 'inactive_button' if the "Load Script" button is clicked more than once. Assigning new procedure to 'click' event of any button does not remove the previous methods, the new procedures are just appended to the previous procedures. So, we can add a single line at the top of test.js like this to achieve that ..

// Remove the old attached events
jQuery('#inactive_button').off('click');

No comments: