jQuery getScript() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
Ajax

Definition

jQuery.getScript(url [, success]) (since 1.0) is a GET shorthand that loads a JavaScript file and executes it in the global context. It is equivalent to $.ajax({ url, dataType: "script", success }).

Syntax

Start with these common calls. Keep them short and readable.

jQuery
$.getScript(url, success)
// ≈
$.ajax({
  url: url,
  dataType: "script",
  success: success
});

// Default: cache: false → timestamp query param
// Returns jqXHR → chain .done() / .fail() / .always()
CallWhat it does
jQueryLearn jQuery.getScript(): the script GET shorthand for $.ajax(), load and execute JavaScript in the global context, success after run, cache:false by default, $.cachedScript() pattern, and .done()/.fail() error handling.

Load jQuery before your script (CDN or local file), then wrap DOM work in $(function () { ... }) when needed.

Parameters

ParameterDescription
Step 1Call $.getScript(url) with an optional success callback.
Step 2jQuery GETs the file with dataType: "script" (cache off by default).
Step 3The script runs globally — plugins attach to window.

Return Value

Return ValueDescription
jQuery objectMost setters and traversing helpers return the jQuery collection so you can chain more methods.

jQuery Examples

Example 1 — Basic $.getScript()

Load dayjs from a CDN and format today’s date after it executes.

jQuery
$("#load").on("click", function () {
  $.getScript(
    "https://cdn.jsdelivr.net/npm/dayjs/dayjs.min.js",
    function (script, textStatus, jqXHR) {
      var today = dayjs().format("MMMM D, YYYY");
      $("#result").text(
        "Today: " + today + " (" + textStatus + ", HTTP " + jqXHR.status + ")"
      );
      console.log(typeof dayjs); // "function"
    }
  );
});
Try It Yourself

How It Works

  1. Click. The handler calls $.getScript() with a CDN URL.
  2. Fetch. jQuery GETs the file as dataType: "script".
  3. Execute. The file runs globally before the callback.

Example 2 — Load a Script, Then Use Its Global

Fetch lodash, then read _.VERSION and run _.map() in the callback.

jQuery
var lodashUrl =
  "https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js";

$.getScript(lodashUrl, function () {
  var doubled = _.map([1, 2, 3], function (n) {
    return n * 2;
  });

  $("#lib-info").text(
    "lodash v" + _.VERSION + " — _.map([1,2,3]) → [" + doubled.join(", ") + "]"
  );
});
Try It Yourself

How It Works

  1. Load. $.getScript() downloads the library file.
  2. Attach. Lodash defines _ on window.
  3. Callback. Success runs only after that attach.

Example 3 — .done() / .fail() Error Handling

Chain Promise handlers so a missing script URL is visible to users.

jQuery
function loadPlugin(url) {
  return $.getScript(url)
    .done(function (script, textStatus, jqXHR) {
      $("#status").text("Loaded (HTTP " + jqXHR.status + ")");
    })
    .fail(function (jqXHR, textStatus, errorThrown) {
      $("#status").text(
        "Failed: " + textStatus + " — " + errorThrown +
        " (HTTP " + jqXHR.status + ")"
      );
    });
}

loadPlugin("https://cdn.jsdelivr.net/npm/dayjs/dayjs.min.js");
// loadPlugin("https://example.com/missing.js"); // → .fail()
Try It Yourself

How It Works

  1. Return jqXHR. $.getScript() returns a Promise-like object.
  2. Success. .done() runs after load + execute.
  3. Failure. 404 / network errors go to .fail().

Frequently Asked Questions

jQuery.getScript() is a shorthand for $.ajax() with dataType "script". Pass a URL and optional success callback — jQuery fetches the file, executes it in the global context, then runs your callback. It returns a jqXHR so you can chain .done(), .fail(), and .always().
After the script has been loaded and executed. That is when globals defined by the file (plugins, utilities) are safe to use.
$.getScript() sets cache to false, which appends a timestamp query parameter so the browser downloads a fresh copy each time. For stable CDN libraries, use the official $.cachedScript() wrapper (cache: true) or $.ajax({ dataType: "script", cache: true }).
Since jQuery 1.5, chain .fail() on the returned jqXHR. Before 1.5, use a global ajaxError handler and check settings.dataType === "script". Prefer jQuery 3.5+ — older versions could still execute unsuccessful HTTP responses that had a script Content-Type.
Both load and run JavaScript. $.getScript() goes through jQuery.ajax(), so you get jqXHR Promises, global Ajax events, and consistent .fail() handling. A raw script element gives more control over attributes but no built-in Promise unless you wrap it.
No. Scripts run with full page privileges. Only load from trusted origins, never pass user-controlled URLs, and prefer allowlists plus Content Security Policy.

Next: .load() Method

Fetch HTML from a URL and inject it into matched elements.

.load() Method tutorial →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful