jQuery Load and Execute JavaScript from Server

This article provides a quick guide on how to dynamically fetch and execute JavaScript files from a web server using jQuery. You will learn about jQuery's built-in $.getScript() method, how to handle callbacks and errors with modern Promise syntax, and how to manage browser caching for dynamic script loading.

Using the $.getScript() Method

jQuery provides a dedicated shorthand method specifically designed for loading and running external JavaScript files: $.getScript(). This method performs an HTTP GET request to retrieve the specified script and automatically executes it in the global context.

The basic syntax is:

$.getScript(url, successCallback);

Basic Implementation

To load and run a script from your server, provide the relative or absolute URL to the file:

$.getScript("https://example.com/js/my-script.js", function(data, textStatus, jqxhr) {
    console.log("Script loaded and executed successfully.");
    
    // You can now call functions defined inside my-script.js
    myCustomFunction();
});

Handling Success and Errors with Promises

$.getScript() returns a jQuery Deferred (jqXHR) object, allowing you to use Promise methods such as .done(), .fail(), and .always() to separate your logic cleanly and catch network or execution errors.

$.getScript("/assets/js/analytics.js")
    .done(function(script, textStatus) {
        console.log("Analytics script loaded successfully.");
    })
    .fail(function(jqxhr, settings, exception) {
        console.error("Failed to load script:", exception);
    });

Managing Script Caching

By default, $.getScript() disables browser caching by appending a timestamp query string (e.g., ?_=1618847291000) to the requested URL. This ensures the browser always fetches the latest version from the server.

If you want the browser to cache the external script to save bandwidth and improve performance, you can use the lower-level $.ajax() function with dataType set to "script" and cache set to true:

$.ajax({
    url: "/assets/js/utility.js",
    dataType: "script",
    cache: true,
    success: function() {
        console.log("Cached script loaded and executed.");
    },
    error: function(xhr, status, error) {
        console.error("Error loading script:", error);
    }
});

Alternatively, you can enable caching globally for all future $.getScript() requests using $.ajaxSetup():

$.ajaxSetup({
    cache: true
});

// This will now use the browser cache if available
$.getScript("/assets/js/utility.js");