jQuery & jQuery UI Documentation

jQuery & jQuery UI

jQuery.getScript()

jQuery.getScript( url [, success(data, textStatus)] ) Returns: jqXHR

Description: Load a JavaScript file from the server using a GET HTTP request, then execute it.

  • version added: 1.0jQuery.getScript( url [, success(data, textStatus)] )

    urlA string containing the URL to which the request is sent.

    success(data, textStatus)A callback function that is executed if the request succeeds.

This is a shorthand Ajax function, which is equivalent to:

$.ajax({
  url: url,
  dataType: "script",
  success: success
});

The callback is passed the returned JavaScript file. This is generally not useful as the script will already have run at this point.

The script is executed in the global context, so it can refer to other variables and use jQuery functions. Included scripts can have some impact on the current page:

$(".result").html("<p>Lorem ipsum dolor sit amet.</p>");

Scripts are included and run by referencing the file name:

$.getScript('ajax/test.js', function(data, textStatus){
   console.log(data); //data returned
   console.log(textStatus); //success
   console.log('Load was performed.');
});

Note: Should you require an additional callback for errors when using the getScript() method, the global ajaxError() callback event may be used to achieve this as follows:

$( "div.log" ).ajaxError(function(e, jqxhr, settings, exception) {
  if (settings.dataType=='script') {
    $(this).text( "Triggered ajaxError handler." );
  }
});

Example:

Load the official jQuery Color Animation plugin dynamically and bind some color animations to occur once the new functionality is loaded.

<!DOCTYPE html>
<html>
<head>
  <style>
.block {
   background-color: blue;
   width: 150px;
   height: 70px;
   margin: 10px;
}</style>
  <script src="http://code.jquery.com/jquery-1.7rc2.js"></script>
</head>
<body>
  
<button id="go">&raquo; Run</button>

<div class="block"></div>

<script>
$.getScript("http://dev.jquery.com/view/trunk/plugins/color/jquery.color.js", function() {
  $("#go").click(function(){
    $(".block").animate( { backgroundColor: "pink" }, 1000)
      .delay(500)
      .animate( { backgroundColor: "blue" }, 1000);
  });
});
</script>

</body>
</html>