jQuery getScript() Method

Beginner
7 min read
Updated: Oct 2026
5 examples
Live preview

What Is getScript()?

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 }).

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

// Default: cache: false → timestamp query param
// Returns jqXHR → chain .done() / .fail() / .always()
NeedUse
Load & run a script$.getScript(url, fn)
Cached CDN script$.ajax({ dataType: "script", cache: true })
JSON GET$.getJSON(url)
Full Ajax control$.ajax({ ... })
Inject HTML into DOM.load(url)

How to Use getScript()

Pass a trusted URL, then use the library only inside the success / .done() callback.

  1. Call $.getScript(url) with an optional success callback.
  2. jQuery GETs the file with dataType: "script" (cache off by default).
  3. The script runs globally — plugins attach to window.
  4. Success / .done() fires after execution — safe place to call the new API.
  5. Chain .fail() for missing URLs or network errors.
PieceRequired?Role
urlYesJavaScript file to load (trusted origin only)
successOptionalfunction(script, textStatus, jqXHR) after execute
Return value—jqXHR Promise (.done / .fail / .always)
CacheDefault offOverride with cache: true via $.ajax() / cachedScript

Pseudocode

Pseudocode
call $.getScript(url, success?)

build GET request with dataType = "script"
if cache is false (default):
    append _=timestamp to url

send request asynchronously

if request succeeds:
    execute script in global context
    call success(script, textStatus, jqXHR)
    resolve jqXHR → .done() handlers
else:
    reject jqXHR → .fail() handlers
    (use jQuery 3.5+ so failed HTTP script responses are not executed)

always → .always() handlers

Cheat Sheet

Keep these facts handy while loading scripts with jQuery.

TopicDetail
Syntax$.getScript( url [, success ] )
ReturnsjqXHR (Promise)
SincejQuery 1.0 · .fail() chaining 1.5+
Equivalent$.ajax({ url, dataType: "script", success })
Success timingAfter load and execute
ContextGlobal — can define / use window APIs
Cache defaultfalse (timestamp busting)
Safe errorsjQuery 3.5+ · always chain .fail()

Live Preview

Load dayjs from a CDN with $.getScript() and run code only after the script executes.

Live demo loads a public CDN script. Needs network access.

Result
Ready — pick an action and click Run.

jQuery Examples

Short, copy-ready snippets. Open DevTools Console, or use Try It Yourself for a live editor.

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.
  4. Use. Call dayjs() inside success — not before.

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.
  4. Call. Use _.map() safely inside the callback.

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().
  4. Version. Prefer jQuery 3.5+ so bad HTTP script responses are not run.

Example 4 — Official $.cachedScript() Pattern

From the jQuery docs: wrap $.ajax() with cache: true for stable CDN files.

jQuery
jQuery.cachedScript = function (url, options) {
  options = $.extend(options || {}, {
    dataType: "script",
    cache: true,
    url: url
  });
  return jQuery.ajax(options);
};

$.cachedScript("https://cdn.jsdelivr.net/npm/dayjs/dayjs.min.js")
  .done(function (script, textStatus) {
    $("#cached-result").text(
      "Cached load: " + textStatus + " — today is " + dayjs().format("YYYY-MM-DD")
    );
  });
Try It Yourself

How It Works

  1. Default. $.getScript() uses cache: false.
  2. Wrapper. cachedScript forces cache: true via $.ajax().
  3. Reuse. The browser may keep the CDN file without busting.
  4. Chain. Still return jqXHR so .done() / .fail() work.

Example 5 — $.getScript() vs $.ajax({ dataType: "script" })

Same network + execution behavior — pick the clearer API for your case.

jQuery
var url = "https://cdn.jsdelivr.net/npm/dayjs/dayjs.min.js";

// A — dedicated shorthand
$.getScript(url, function () {
  $("#result-a").text("getScript: " + dayjs().format("HH:mm:ss"));
});

// B — explicit $.ajax()
$.ajax({
  url: url,
  dataType: "script",
  success: function () {
    $("#result-b").text("ajax script: " + dayjs().format("HH:mm:ss"));
  }
});
Try It Yourself

How It Works

  1. Same transport. Both use the script dataType path.
  2. Shorthand. $.getScript() is the readable one-liner.
  3. Flexible. $.ajax() adds cache, beforeSend, headers, etc.
  4. Choose. Common load → getScript; custom options → ajax / cachedScript.

Edge Cases & Pitfalls

Check these before loading remote scripts in production.

security

Scripts run with full page power

Only load from trusted origins. Never pass user-controlled URLs to $.getScript().

timing

Use APIs only after success

Code before the callback cannot assume the library exists. Bind UI in .done() / success.

cache

Cache is off by default

cache: false adds a timestamp. For stable CDN files, use $.cachedScript() or $.ajax({ cache: true }).

version

Prefer jQuery 3.5+

Older versions could execute unsuccessful HTTP responses that still had a script Content-Type.

modules

Not an ES module loader

$.getScript() runs classic scripts globally. Use native type="module" / import() for ES modules.

Browser Support

jQuery.getScript() has been part of jQuery since 1.0. Promise .fail() chaining needs 1.5+. Prefer jQuery 3.5+ for safer handling of failed script HTTP responses.

✓ Stable · jQuery 1.0+

jQuery.getScript()

Works in every browser that runs your loaded jQuery version. Prefer a current jQuery 3.x (3.5+) build. Requires jQuery Ajax — native dynamic script tags and ES modules are separate APIs.

100% With jQuery Ajax
Google Chrome All versions · Desktop & Mobile
Full support
Mozilla Firefox All versions · Desktop & Mobile
Full support
Apple Safari All versions · macOS & iOS
Full support
Microsoft Edge All versions · Chromium & Legacy
Full support
Internet Explorer IE 6+ · Legacy environments
Full support
Opera All modern versions
Full support
getScript Universal

Bottom line: Safe for trusted CDN / same-origin scripts. Always chain .fail() and keep URLs allowlisted.

Performance Notes

ApproachCostBest for
One lazy $.getScript()CheapOn-demand plugins / widgets
cachedScript for CDN libsCheaper repeatsStable third-party files
Many uncached getScript callsExpensiveAvoid — cache or bundle instead

Load scripts only when needed. Busting cache on every call is fine in development; enable caching for production CDN libraries.

Key Takeaways

  • Role: GET + execute JavaScript globally (dataType: "script").
  • Call: $.getScript(url [, success]) — use APIs in the callback.
  • Cache: off by default; use cachedScript / cache: true for CDN libs.
  • Safety: trusted URLs only · jQuery 3.5+ · always chain .fail().

One line: $.getScript() loads and runs a remote script — call its APIs only after success, and never from untrusted URLs.

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() tutorial →

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