jQuery.getScript()

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

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 should have some impact on the current page:

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

The script can then be included and run by referencing the file name:

$.getScript('ajax/test.js', function() {
  alert('Load was performed.');
});

Examples:

Example: We load the new 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="https://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
	<button id="go">&raquo; Run</button>

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

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

Demo:

Example: Load the test.js JavaScript file and execute it.

$.getScript("test.js");

Example: Load the test.js JavaScript file and execute it, displaying an alert message when the execution is complete.

$.getScript("test.js", function(){
   alert("Script loaded and executed.");
 });