jQuery.getScript()S2C Home « Ajax « jQuery.getScript()

Asynchronous HTTP (Ajax) JavaScript load and execute request.

Description

The jQuery.getScript() Ajax method, allows us to load and execute a JavaScript file from the server, using a HTTP GET request.

Shorthand version $.getScript()

  • Browsers operate the 'same origin policy', which means a request can not successfully retrieve data from a different domain, subdomain, or protocol. jQuery 'Ajax' requests are subject to this security restriction, the exceptions being requests made with a datatype of 'script' or 'jsonp'.
  • The jQuery.getScript() method returns a jqXHR object which is a superset of the browser's native XMLHttpRequest object. The jqXHR object implements the Promise interface, giving it all the properties, methods, and behavior of a Promise. See the lesson on the Deferred object for details of this. For standardization with the Deferred object, the jqXHR object also provides .always(), .done() and .fail() methods. These methods take a function argument that is called when the jQuery.getScript() request terminates and the function receives the same arguments as the same-named .complete().success() and .error() setting callbacks respectively. This allows assignment of multiple callbacks for a single request as well as assigning callbacks after the request has completed. For completed requests, the callback is fired immediately.
    • It should be noted that .complete().success() and .error() callbacks will be deprecated from use on request completion from jQuery 1.8. This is for completion processing only and the Ajax settings will still have these values. Best practice is to use .always(), .done() and .fail() methods on request completion to future proof code.
  • A jqXHR object will expose the following properties and methods for backward compatibility with the XMLHttpRequest object:
jqXHR Object Description
Methods
abort()Cancels the currently executing request.
getAllResponseHeaders()Returns a string containing the names and value of all response headers.
getResponseHeader(name)Returns the value of the specified response headers.
.overrideMimeType()Used in the beforeSend() callback function, to modify the response content-type header.
setRequestHeader(name, value)Set a request header using the specified name and value.
Properties
readyStateAn integer indicating the current state of the request.
responseTextUnderlying request responded with text.
responseXMLUnderlying request responded with xml.
statusResponse status code returned from the server.
statusTextStatus text message returned by the response.

Syntax

Signature Description
jQuery.getScript( url
                [,function(data,textStatus,jqXHR)])
Load and execute a JavaScript file from the server, using a HTTP GET request.

Parameters

Parameter Description Type
url A string containing the URL to send the request to.String
function(data, textStatus, jqXHR) A callback function executed when the request succeeds.Function

Return

A jqXHR object.

jQuery.getScript( url
       [, function(data, textStatus, jqXHR)] )
ExamplesTop

Load and execute a JavaScript file from the server, using a HTTP GET request.

This is a shorthand Ajax function, which is equivalent to using the jQuery.ajax() method as follows:


$.ajax({
  url: url,
  dataType: 'script',
  data: data,
  cache: false,
  success: callback
});

In the example below when we press the left button the first time we use the jQuery.getScript() method with a url. The script for the 'get5.js' asset executes and appends a message to this page.

When we press the right button the first time we use the jQuery.getScript() method with a url and a success handler. The script for the 'get5.js' asset executes and appends a message to this page and the success callback is invoked and also appends a message.


$(function(){
  $('#btn6').one('click', function(){
    $.getScript( "../js/get5.js" );
  });
  $('#btn7').one('click', function(){
    $.getScript( "../js/get5.js", function() {
      $('#div3').append('The request was a success! <br>');
    });
  });
});

/*
 * The code for the external Javascript file called from $.ajax() (url: "../js/get5.js")
 * is shown below.
 */
$(function(){
  var someText = 'Passing some text. ';
  $('#div3').append('Message from get5.js: ' + someText + '<br>');
});

div3. Some initial text.

Press the button below to action the above code: