jQuery getScript() Method

Beginner
⏱️ 12 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Ajax Shorthands

What You’ll Learn

$.getScript() is jQuery’s dedicated JavaScript GET shorthand. This tutorial covers the official signature, how it maps to $.ajax() with dataType: "script", global script execution after load, the success callback fired only after execution completes, default cache: false timestamp behavior, the official $.cachedScript() wrapper, chaining .done() and .fail() on the returned jqXHR, jQuery 3.5.0 HTTP error semantics, and when to upgrade to full $.ajax().

01

Script Shorthand

$.getScript(url, ...)

02

dataType script

Fetch + execute

03

Global Context

window scope

04

success

After load + run

05

jqXHR

done/fail/always

06

Cache Control

$.cachedScript()

Introduction

Not every library belongs in your HTML on first paint. Color animation plugins, charting libraries, and date utilities are often loaded on demand — when a user opens a panel, clicks a button, or scrolls to a widget. jQuery makes that one line with $.getScript(). Pass a URL and an optional callback; jQuery sends an asynchronous HTTP GET request, injects the response as executable JavaScript in the global context, and invokes your function once the script has loaded and run.

Under the hood, $.getScript() is not a separate transport — it is a thin wrapper around jQuery.ajax() with dataType: "script" preset and cache defaulting to false. That means you inherit the same jqXHR return value, global Ajax events on document, and Promise-style chaining. When your needs outgrow a one-liner — cached production loads, custom headers, or global: false — you drop down to $.ajax() or the official $.cachedScript() pattern without changing mental models.

Understanding jQuery.getScript()

jQuery.getScript() loads a JavaScript file from a server using an HTTP GET request, then executes it. The method returns immediately with a jqXHR object while the network call runs in the background. If you pass a success function, jQuery calls it only after the script body has been retrieved, evaluated, and executed — not merely downloaded.

Because execution happens in the global context, loaded scripts can define functions, attach plugins to jQuery.fn, and reference variables already on window. That power comes with responsibility: only load scripts from origins you trust. A malicious response runs with full page privileges.

💡
Beginner Tip

Chain .fail() on the jqXHR returned by $.getScript(). Network errors and 404 responses route to .fail(), not the success callback. Since jQuery 1.5, Promise-style handlers are the recommended error path — prior versions relied on the global ajaxError event.

📝 Syntax

The official jQuery API accepts one signature:

Positional arguments — jQuery.getScript( url [, success ] )

jQuery
jQuery.getScript( url [, success ] )

URL first, optional success callback. Unlike $.get(), there is no data argument — script requests load a file by URL only.

Equivalence to $.ajax()

These two calls are identical:

jQuery
// Shorthand
$.getScript( url, success );

// Expanded — what jQuery does internally
$.ajax( {
  url: url,
  dataType: "script",
  success: success
} );

success callback signature

  • script — the raw script text returned by the server (same as the first argument historically named data in API docs).
  • textStatus — string such as "success" when the request completes without transport errors.
  • jqXHR — the same jqXHR object returned by $.getScript(); inspect jqXHR.status for the HTTP status code.

Return value

  • $.getScript() returns a jqXHR object — chain .done(), .fail(), and .always().
  • The success callback fires after the script is loaded and executed — globals defined by the file are available when your callback runs.
  • Deprecated jqXHR methods .success(), .error(), and .complete() were removed in jQuery 3.0 — use .done() / .fail() / .always().
  • Call jqXHR.abort() to cancel an in-flight script request before it completes.

⚡ Quick Reference

GoalCode
Basic script load (fire and forget)$.getScript("https://cdn.jsdelivr.net/npm/dayjs/dayjs.min.js")
Load script with success callback$.getScript(url, function(script, status, xhr) { ... })
Chain success handler$.getScript(url).done(function(script, status) { ... })
Handle errors$.getScript(url).fail(function(xhr, status, err) { ... })
Load plugin then use it$.getScript(url, function() { $(".el").pluginMethod(); })
Cached script (official pattern)$.cachedScript(url).done(fn)
Enable cache globally$.ajaxSetup({ cache: true })
Full $.ajax() equivalent$.ajax({ url, dataType: "script", success: fn })
Cancel requestvar req = $.getScript(...); req.abort();

📋 $.getScript() vs dynamic <script> vs $.ajax() vs ES modules

Four ways to load JavaScript at runtime — pick the shortest readable form or the API with the control you need.

$.getScript()
script GET shorthand

$.getScript(url, success) — one-liner for dynamic loads; dataType: "script" preset; cache defaults to false

<script> tag
createElement

Native DOM injection — full control over async/defer/SRI attributes; no jqXHR unless you wrap onload/onerror yourself

$.ajax()
full control

$.ajax({ url, dataType: "script", cache: true }) — every setting exposed; basis for $.cachedScript()

ES modules
import()

import("https://cdn.skypack.dev/lodash") — native dynamic import; module scope; no jQuery dependency

Use $.getScript() for simple on-demand script loads in jQuery projects. Use dynamic <script> tags when you need SRI or fine-grained attribute control without jQuery. Use $.ajax() or $.cachedScript() when you need cache: true, headers, or global: false. Use ES import() in modern vanilla JS or bundler-free module workflows.

Examples Gallery

Five progressive examples from a basic CDN utility load through global library usage, jqXHR error handling, the official $.cachedScript() pattern, and side-by-side equivalence with $.ajax({ dataType: "script" }). Each links to a Try-it lab where you can edit and run the code in the browser.

📚 Core Patterns

Load and run external JavaScript with the positional $.getScript() signature.

Example 1 — Basic $.getScript() — load a CDN utility

Fetch dayjs from jsDelivr and display today’s formatted date once the script loads and executes.

jQuery
$( "#load" ).on( "click", function() {
  $.getScript(
    "https://cdn.jsdelivr.net/npm/dayjs/dayjs.min.js",
    function( script, textStatus, jqXHR ) {
      // dayjs is now on window — script has loaded AND executed
      var today = dayjs().format( "MMMM D, YYYY" );
      $( "#result" ).html(
        "<strong>Today:</strong> " + today +
        " <small>(" + textStatus + ", HTTP " + jqXHR.status + ")</small>"
      );
      console.log( typeof dayjs ); // "function"
    }
  );
} );
Try It Yourself

How It Works

The second argument is the success callback — jQuery invokes it with (script, textStatus, jqXHR) only after execution completes. Because dataType: "script" is preset, you call dayjs() directly inside the callback without a separate eval step.

Example 2 — Load a script then use the global it defines

Adapted from common plugin-loading patterns: fetch lodash from cdnjs, then read _.VERSION and demonstrate a utility method.

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

$.getScript( lodashUrl, function() {
  // _ is now on window — defined by the loaded script
  var version = _.VERSION;
  var doubled = _.map( [ 1, 2, 3 ], function( n ) {
    return n * 2;
  } );

  $( "#lib-info" ).html(
    "<strong>lodash</strong> v" + version +
    " loaded — _.map([1,2,3]) → [" + doubled.join( ", " ) + "]"
  );
} );
Try It Yourself

How It Works

Libraries designed for <script> tags attach to window. The success callback is the safe place to call them — code before the callback cannot assume the library exists. This mirrors the official jQuery Color plugin demo pattern: load first, bind behavior in the callback.

Example 3 — .done() / .fail() — invalid URL error handling

Request a non-existent script URL — chain .fail() so users see feedback instead of a silent broken feature.

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

// Valid CDN script
loadPlugin( "https://cdn.jsdelivr.net/npm/dayjs/dayjs.min.js" );

// 404 — triggers .fail()
$( "#load-bad" ).on( "click", function() {
  loadPlugin( "https://cdn.jsdelivr.net/npm/this-library-does-not-exist-xyz/plugin.min.js" );
} );
Try It Yourself

How It Works

Since jQuery 1.5, chain .fail() on the returned jqXHR. Prior to 1.5, register $(document).on("ajaxError", ...) and check settings.dataType === "script". Network failures and HTTP errors route to .fail(), not the legacy success callback.

📈 Caching & Equivalence

Use the official $.cachedScript() wrapper and compare with $.ajax({ dataType: "script" }).

Example 4 — Official $.cachedScript() wrapper pattern

From the jQuery API docs: define a helper that uses $.ajax() with cache: true and dataType: "script" for production libraries that rarely change.

jQuery
jQuery.cachedScript = function( url, options ) {
  // Allow user to set any option except for dataType, cache, and url
  options = $.extend( options || {}, {
    dataType: "script",
    cache: true,
    url: url
  } );

  // Use $.ajax() since it is more flexible than $.getScript
  // Return the jqXHR object so we can chain callbacks
  return jQuery.ajax( options );
};

// Usage — browser may reuse cached copy (no timestamp param)
$.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

$.getScript() sets cache: false by default, appending a timestamp to bust caches. The official $.cachedScript() pattern inverts that for stable CDN URLs. Alternatively, set $.ajaxSetup({ cache: true }) globally — but the wrapper keeps cache behavior explicit per call.

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

Both calls produce identical network requests and execution behavior — $.getScript() is simply clearer when you always load JavaScript.

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

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

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

// Both expand internally to the same transport:
// GET url → inject <script> → execute in global context → success fires
Try It Yourself

How It Works

When you need cache: true, beforeSend, or global: false, use $.ajax() directly or the $.cachedScript() wrapper. $.getScript() covers the common case — URL plus optional success — making script-only requests easier to read and review in code.

🚀 Common Use Cases

  • Lazy-load plugins — fetch jQuery UI widgets, color animation, or chart libraries only when a user opens the relevant panel.
  • Conditional features — load a mapping SDK when the user navigates to a map view instead of on every page load.
  • Third-party widgets — inject chat, analytics, or social embed scripts on demand after consent or interaction.
  • A/B test bundles — load variant-specific JavaScript from different URLs based on experiment assignment.
  • Admin-only tools — load rich editors or data-grid libraries only for authenticated admin routes.
  • Progressive enhancement — keep the initial HTML lean; enhance with script modules as capabilities are needed.

🧠 How $.getScript() Works Internally

1

Expand to $.ajax()

$.getScript() maps positional args to { url, dataType: "script", success } with cache: false and delegates to jQuery.ajax().

$.ajax()
2

Return jqXHR immediately

Caller receives a jqXHR object right away — attach .done() / .fail() before or after the response arrives.

jqXHR
3

Append cache-bust param

With default cache: false, jQuery adds a timestamp query parameter so the browser fetches a fresh copy each call.

cache
4

Inject & execute script

The script transport creates a <script> element, sets src, and evaluates the response in the global window context.

dataType
5

success + .done()

After execution completes, the legacy success callback and chained .done() handlers run with (script, textStatus, jqXHR).

.done()
6

Error path or ajaxComplete

Network failures and HTTP errors invoke .fail(). Global ajaxComplete fires either way. Prior to jQuery 3.5.0, some failed script responses still executed.

📝 Notes

  • $.getScript() is asynchronous — code after the call runs before the script loads and executes.
  • It is shorthand for $.ajax() with dataType: "script" — same jqXHR, same global Ajax events.
  • Global execution: loaded scripts run in the window context and can modify your page — only load URLs you trust completely.
  • Security: never pass user-controlled URLs to $.getScript(); treat dynamic script loads like eval() from a remote source.
  • Cache default: cache: false appends a timestamp query param — use $.cachedScript() or $.ajaxSetup({ cache: true }) for stable CDN URLs.
  • Success timing: the callback fires after load and execution — globals defined by the file exist when your callback runs.
  • Prefer .done() / .fail() / .always() over deprecated jqXHR .success() / .error() / .complete() (removed in jQuery 3.0).
  • jQuery 3.5.0+: unsuccessful HTTP responses with script Content-Type are no longer executed — upgrade for safer error semantics.

Browser Support

jQuery.getScript() is part of jQuery’s core Ajax module — not a native DOM API. It works wherever jQuery’s Ajax transport runs: all browsers supported by your jQuery version, including legacy IE with supported jQuery builds.

jQuery 1.0+

jQuery.getScript() method

Supported in jQuery 1.x, 2.x, and 3.x across all modern browsers and IE with supported jQuery builds. jqXHR promise methods (.done, .fail, .always) arrived in jQuery 1.5. Prior to jQuery 3.5.0, unsuccessful HTTP responses with script Content-Type were still executed. Cross-domain script loads work via standard script tag injection — no CORS required for execution.

100% With jQuery
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 in any jQuery project. Use $.getScript() for simple script loads; $.cachedScript() or $.ajax() when you need cache: true or extra settings; dynamic import() is the native alternative when jQuery is not loaded.

Conclusion

jQuery.getScript() is the fastest path from URL to executed JavaScript for on-demand plugin and utility loads. Learn the signature (url, success), chain .fail() for network and HTTP errors, and reach for $.cachedScript() or full $.ajax() when you need cached production loads or extra settings.

When you need to inject HTML from the server into a page region, continue with the jQuery .load() tutorial. Every $.getScript() call can trigger global Ajax events on document — explore ajaxStart after param for page-wide loading indicators.

💡 Best Practices

✅ Do

  • Chain .fail() on every $.getScript() so users see load failures
  • Load scripts only from trusted origins — CDNs you control or well-known providers
  • Use $.cachedScript() for stable production URLs that rarely change
  • Put library calls inside the success callback — globals are not ready before it runs
  • Upgrade to $.ajax() when you need headers, global: false, or custom cache settings

❌ Don’t

  • Pass user-supplied URLs to $.getScript() — that is a remote code execution vector
  • Assume errors surface automatically — chain .fail() or register ajaxError
  • Load large libraries on every page when only one widget needs them
  • Use deprecated jqXHR .success() / .error() / .complete() in jQuery 3.x
  • Leave in-flight script requests running after SPA navigation — call .abort() on teardown

Key Takeaways

Knowledge Unlocked

Six things to remember about $.getScript()

Script in, globals out, chain fail().

6
Core concepts
type 02

dataType script

Fetch + execute

Auto
glob 03

Global Context

window scope

Execute
cb 04

success

After load + run

Callback
xhr 05

jqXHR

done/fail/always

Promise
c 06

Cache Control

$.cachedScript()

Production

❓ Frequently Asked Questions

jQuery.getScript() is a shorthand for $.ajax() configured as a GET request with dataType set to "script". Pass a URL and optional success callback — jQuery fetches the JavaScript file asynchronously, injects and executes it in the global context, then invokes your callback. It returns a jqXHR object so you can chain .done(), .fail(), and .always(). Use it when you need to load a third-party plugin or utility on demand without adding a static <script> tag to your HTML.
Both load and execute JavaScript, but $.getScript() routes through jQuery.ajax() — you get a jqXHR return value, Promise-style .done()/.fail() chaining, global Ajax events (ajaxStart, ajaxComplete), and consistent error handling since jQuery 1.5. A raw document.createElement("script") approach gives you full control over async/defer and attributes but no built-in Promise interface unless you wrap it yourself. Prefer $.getScript() in jQuery projects; use native script tags or ES modules when jQuery is not loaded.
By default, $.getScript() sets cache to false internally, which appends a timestamp query parameter to the URL so the browser fetches a fresh copy on every call. That prevents stale plugin code during development. For production libraries that rarely change, override globally with $.ajaxSetup({ cache: true }) or use the official $.cachedScript() wrapper pattern that passes cache: true to $.ajax() while keeping dataType: "script".
Scripts loaded by $.getScript() run in the global window context with the same privileges as your page — they can read cookies, modify the DOM, call your functions, and exfiltrate data. Only load JavaScript from origins you trust completely. Never pass user-controlled URLs to $.getScript(). A compromised or malicious CDN response executes immediately. Prefer Subresource Integrity (SRI) on static tags when possible; dynamic loads require strict URL allowlists and Content Security Policy.
They are functionally equivalent — $.getScript(url, success) expands to $.ajax({ url, dataType: "script", success }) with cache defaulting to false. Use $.getScript() for the common one-liner. Use $.ajax() or $.cachedScript() when you need extra options: cache: true, beforeSend, headers, global: false, or a custom error handler. $.cachedScript() from the official docs wraps $.ajax() with cache: true and dataType: "script" preset.
Since jQuery 1.5, chain .fail() on the returned jqXHR: $.getScript(url).done(fn).fail(function(jqxhr, settings, exception) { ... }). Prior to 1.5, register a global ajaxError handler on document and check settings.dataType === "script". Network failures and 404 responses trigger .fail(). Note: prior to jQuery 3.5.0, unsuccessful HTTP responses that still returned a script Content-Type were executed anyway — upgrade to jQuery 3.5+ for safer error semantics.
Did you know?

$.getScript() has existed since jQuery 1.0 — the same release as $.get(), $.post(), and $.getJSON(). The object returned only became a full jqXHR with Promise methods in jQuery 1.5. By default it sets cache: false, unlike most other Ajax shorthands — which is why the official docs include a separate $.cachedScript() helper. Under the hood, every call still routes through jQuery.ajax() with dataType: "script" preset — which is why global ajaxStart and ajaxStop fire unless you use full $.ajax() with global: false.

Next: jQuery .load() Method

Fetch HTML from the server and inject it into matched elements — tabs, modals, and partials.

jQuery .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.

6 people found this page helpful