← Back to jQuery Course | Chapter 9: AJAX Basics | Lesson 6 of 7

Loading Scripts with getScript()

The getScript method loads a JavaScript file from a URL and runs it. It is useful for loading extra scripts when needed.
Syntax
javascript
$.getScript(url, function () {
  // script loaded
});

What is getScript()?

$.getScript() fetches a JavaScript file from a URL over AJAX and executes it as soon as it arrives, effectively injecting and running a script tag dynamically. This lets a page pull in extra code only when it's actually needed.

Example: What is getScript()?

javascript
<!DOCTYPE html>
<html>
<head>
  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <style>
    button { padding:6px 14px; margin:4px; background:#2c6aa0; color:white; border:none; border-radius:4px; cursor:pointer; }
    #resetBtn { background:white; color:#2c6aa0; border:1px solid #2c6aa0; }
    #output { margin-top:10px; padding:8px; border:1px solid #ccc; border-radius:4px; background:#f7f7f7; font-family:monospace; min-height:24px; }
  </style>
</head>
<body>
  <button id="runBtn">Run</button>
  <button id="resetBtn">Reset</button>
  <div id="output"></div>
  <script>

    $("#runBtn").click(function() {
      $.getScript("https://code.jquery.com/jquery-3.7.1.min.js", function() {
        $("#output").text("Script loaded and executed");
      });
    });

    $("#resetBtn").click(function() {
      $("#output").empty();
    });
  </script>
</body>
</html>

Use a Success Callback

The done callback runs after the script has loaded and executed successfully, which is the safe place to start calling any functions the new script defines. Calling those functions before the script has actually finished loading would fail, since they wouldn't exist yet.

Example: Use a Success Callback

javascript
<!DOCTYPE html>
<html>
<head>
  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <style>
    button { padding:6px 14px; margin:4px; background:#2c6aa0; color:white; border:none; border-radius:4px; cursor:pointer; }
    #resetBtn { background:white; color:#2c6aa0; border:1px solid #2c6aa0; }
    #output { margin-top:10px; padding:8px; border:1px solid #ccc; border-radius:4px; background:#f7f7f7; font-family:monospace; min-height:24px; }
  </style>
</head>
<body>
  <button id="runBtn">Run</button>
  <button id="resetBtn">Reset</button>
  <div id="output"></div>
  <script>

    $("#runBtn").click(function() {
      $.getScript("https://code.jquery.com/jquery-3.7.1.min.js").done(function() {
        $("#output").text("Safe to use functions from the new script now");
      });
    });

    $("#resetBtn").click(function() {
      $("#output").empty();
    });
  </script>
</body>
</html>

Handle Script Errors

A script may fail to load -- due to a bad URL, a network error, or a blocked request -- and chaining .fail() lets you handle that case and show a useful message instead of leaving broken functionality with no explanation.

Example: Handle Script Errors

javascript
<!DOCTYPE html>
<html>
<head>
  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <style>
    button { padding:6px 14px; margin:4px; background:#2c6aa0; color:white; border:none; border-radius:4px; cursor:pointer; }
    #resetBtn { background:white; color:#2c6aa0; border:1px solid #2c6aa0; }
    #output { margin-top:10px; padding:8px; border:1px solid #ccc; border-radius:4px; background:#f7f7f7; font-family:monospace; min-height:24px; }
  </style>
</head>
<body>
  <button id="runBtn">Run</button>
  <button id="resetBtn">Reset</button>
  <div id="output"></div>
  <script>

    $("#runBtn").click(function() {
      $.getScript("https://example.com/missing-script-404.js").fail(function() {
        $("#output").text("Script failed to load");
      });
    });

    $("#resetBtn").click(function() {
      $("#output").empty();
    });
  </script>
</body>
</html>

Load a Script on Demand

Loading a script only when it's actually needed, rather than including it in every page's initial load, is called loading on demand, and it can keep the initial page lighter and faster. getScript() is the standard jQuery way to implement this pattern.

Example: Load a Script on Demand

javascript
<!DOCTYPE html>
<html>
<head>
  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <style>
    button { padding:6px 14px; margin:4px; background:#2c6aa0; color:white; border:none; border-radius:4px; cursor:pointer; }
    #resetBtn { background:white; color:#2c6aa0; border:1px solid #2c6aa0; }
    #output { margin-top:10px; padding:8px; border:1px solid #ccc; border-radius:4px; background:#f7f7f7; font-family:monospace; min-height:24px; }
    #demo :where(p, div, span, li, h1, h2, h3, h4, td, th, blockquote, label, section, article, aside) { border:1px solid #4a7fb5; background:#eaf2fb; padding:6px 10px; margin:4px 0; border-radius:4px; }
    #demo :where(ul, ol) { border:1px dashed #888; background:#fafafa; padding:8px 8px 8px 32px; margin:6px 0; }
    #demo :where(table) { border-collapse:collapse; }
    #demo :where(td, th) { border-radius:0; }
    #demo :where(input, select, textarea) { margin:4px 0; }
  </style>
</head>
<body>
  <button id="resetBtn">Reset</button>
  <section id="demo">
    <button id="btn">Load Feature</button>

  </section>
  <div id="output"></div>
  <script>
    var original = $("#demo").html();

    function init() {
      $("#btn").on("click", function() {
        $.getScript("https://code.jquery.com/jquery-3.7.1.min.js", function() {
          $("#output").append($("<div>").text("Feature script loaded on demand"));
        });
      });
    }
    init();

    $("#resetBtn").click(function() {
      $("#demo").html(original);
      $("#output").empty();
      init();
    });
  </script>
</body>
</html>

Small getScript() Project

getScript() is helpful when an extra JavaScript library or plugin is needed only for a particular feature, like a chart library that's only used on one specific page. Loading it on demand avoids making every visitor download code most of them will never use.

Example: Small getScript() Project

javascript
<!DOCTYPE html>
<html>
<head>
  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <style>
    button { padding:6px 14px; margin:4px; background:#2c6aa0; color:white; border:none; border-radius:4px; cursor:pointer; }
    #resetBtn { background:white; color:#2c6aa0; border:1px solid #2c6aa0; }
    #output { margin-top:10px; padding:8px; border:1px solid #ccc; border-radius:4px; background:#f7f7f7; font-family:monospace; min-height:24px; }
    #demo :where(p, div, span, li, h1, h2, h3, h4, td, th, blockquote, label, section, article, aside) { border:1px solid #4a7fb5; background:#eaf2fb; padding:6px 10px; margin:4px 0; border-radius:4px; }
    #demo :where(ul, ol) { border:1px dashed #888; background:#fafafa; padding:8px 8px 8px 32px; margin:6px 0; }
    #demo :where(table) { border-collapse:collapse; }
    #demo :where(td, th) { border-radius:0; }
    #demo :where(input, select, textarea) { margin:4px 0; }
  </style>
</head>
<body>
  <button id="resetBtn">Reset</button>
  <section id="demo">
    <button id="loadChart">Load Chart Library</button>

  </section>
  <div id="output"></div>
  <script>
    var original = $("#demo").html();

    function init() {
      $("#loadChart").on("click", function() {
        $.getScript("https://code.jquery.com/jquery-3.7.1.min.js", function() {
          $("#output").append($("<div>").text("Chart library ready"));
        });
      });
    }
    init();

    $("#resetBtn").click(function() {
      $("#demo").html(original);
      $("#output").empty();
      init();
    });
  </script>
</body>
</html>
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Using a script's functions right after $.getScript(...) instead of inside its .done() callback, so they are not defined yet.
  2. Forgetting .fail(), so a wrong URL or blocked request fails with no visible feedback.
  3. Loading the same script repeatedly on every click, which re-executes it and can duplicate event handlers and side effects.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.