jQuery: the $.getScript() method

The jQuery's $.getScript() method is an AJAX method that allows us to load a JavaScript file and execute it in the global context. The peculiarity of this method is that it doesn't execute scripts which contain syntactic errors. However, if a script contains errors, nothing will be shown in your JavaScript console. For that reason, it's recommended to set up an error handler using the ajaxError event. Let's see how.

We want to load the following script:

var Library = {

  create: function(options) {
  
    options = {
      element: '<p/>',
      content: 'Test',
      target: 'body'
    };
    
    $(options.element).
    text(options.content).
    appendTo(options.target);
  
  
  },

  init: function() {
  
    this.create();
  
  }


};

When the script is loaded, we want to execute the init() method of the Library object. First, we need to take care of any possible errors:

$('#log').ajaxError(function(e, jqxhr, settings, exception) {
    
    $(this).text(e + ' ' + jqxhr + ' ' + exception);
    
});

Obviously you can simply log all these data to the JavaScript console. Then we can use $.getScript():

$.getScript('jquery-get-script-test.js', function() {
  
    Library.init();
  
});

As you can see, the main method of our object is executed as if it was already present in the page. You can see the demo below.

Demo

Live demo

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.