jQuery ajax - getScript() method

Example

Obtain and run a JavaScript file via AJAX requests:

$("button").click(function(){
  $.getScript("demo_ajax_script.js");
});

Try it yourself

Definition and Usage

The getScript() method loads and executes a JavaScript file via an HTTP GET request.

Syntax

jQuery.getScript(url,success(response,status});
Parameters Description
url The URL string to be requested.
success(response,status)

Optional. Specifies the callback function to be executed after the request is successful.

Additional Parameters:

  • response - Includes the result data from the request
  • status - Includes the request status ("success", "notmodified", "error", "timeout", or "parsererror")

Detailed Description

This function is a shorthand for the Ajax function, equivalent to:

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

The callback function passed in the returned JavaScript file. This is usually not very useful because the script has already been executed by then.

The loaded script is executed in the global environment, so it can refer to other variables and use jQuery functions.

For example, loading a test.js file that contains the following code:

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

By referencing this filename, you can load and run this script:

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

Note:Before jQuery 1.2 version, getScript could only call JavaScript files from the same domain. In version 1.2, you can call JavaScript files across domains. Note: Safari 2 or earlier versions cannot execute scripts in the global scope synchronously. If scripts are added through getScript, please add a delay function.

More examples

Example 1

Load and execute test.js:

$.getScript("test.js");

Example 2

Load and execute test.js, and display the message after successful execution:

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

Example 3

Load jQuery official color animation plugin After successful binding, color change animation is bound:

HTML code:

<button id="go">Run</button>
<div class="block"></div>

jQuery code:

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