Force jQuery AJAX to Evaluate Response as Script

This article explains how to force jQuery AJAX requests to treat and execute server responses as JavaScript code. By default, jQuery automatically detects response types based on MIME headers, but server misconfigurations or specific architecture needs may require explicit execution. You will learn how to configure the dataType parameter in standard AJAX calls, use the dedicated shorthand method, and manually execute returned code globally when dealing with non-standard MIME types.

Use the dataType Setting

The primary and cleanest method to force script execution is defining the dataType parameter as "script" within the $.ajax() configuration object. This forces jQuery to execute the response text in the global context as soon as it arrives, regardless of the Content-Type header sent by the server.

$.ajax({
    url: "https://example.com/api/script-endpoint",
    dataType: "script",
    success: function(data, textStatus, jqXHR) {
        console.log("Script loaded and executed successfully.");
    },
    error: function(jqXHR, textStatus, errorThrown) {
        console.error("Failed to load or execute script:", errorThrown);
    }
});

When dataType: "script" is set, jQuery automatically inserts a dynamic <script> tag into the document head for cross-domain requests, or evaluates the response content via $.globalEval() for same-domain requests.

Use the $.getScript() Shorthand

If you are performing a GET request, jQuery provides a built-in helper function called $.getScript(). This method acts as an alias for a GET AJAX call configured with dataType: "script".

$.getScript("https://example.com/dynamic-code.js")
    .done(function(script, textStatus) {
        console.log("Script executed automatically.");
    })
    .fail(function(jqXHR, settings, exception) {
        console.error("Execution failed:", exception);
    });

By default, $.getScript() sets the cache option to false, appending a timestamp query string to the URL to prevent browser caching.

Manually Execute Responses with $.globalEval()

When a server returns JavaScript with an incorrect MIME type (such as text/plain or application/octet-stream) and modifying the dataType causes processing issues, you can accept the response as plain text and force execution using $.globalEval().

$.ajax({
    url: "https://example.com/custom-script",
    dataType: "text",
    success: function(response) {
        // Runs the code globally, equivalent to native script execution
        $.globalEval(response);
    }
});

Using $.globalEval() is safer and more reliable than standard JavaScript eval(), as it guarantees the script executes within the window's global scope rather than inside the local function scope of the AJAX callback.

Security Considerations

Forcing script evaluation directly from HTTP responses poses security risks, primarily Cross-Site Scripting (XSS). Only evaluate responses from strictly trusted endpoints, validate that the connection uses HTTPS to avoid man-in-the-middle attacks, and avoid using user-controlled parameters to construct the target script URL.