Script tags now used for most async requests in 4.0
The full logic for whether to use the script tag is implemented by this function:
function canUseScriptTag( s ) {
// A script tag can only be used for async, cross domain or forced-by-attrs requests.
// Requests with headers cannot use a script tag. However, when both `scriptAttrs` &
// `headers` options are specified, both are impossible to satisfy together; we
// prefer `scriptAttrs` then.
// Sync requests remain handled differently to preserve strict script ordering.
return s.scriptAttrs || (
!s.headers &&
(
s.crossDomain ||
// When dealing with JSONP (`s.dataTypes` include "json" then)
// don't use a script tag so that error responses still may have
// `responseJSON` set. Continue using a script tag for JSONP requests that:
// * are cross-domain as AJAX requests won't work without a CORS setup
// * have `scriptAttrs` set as that's a script-only functionality
// Note that this means JSONP requests violate strict CSP script-src settings.
// A proper solution is to migrate from using JSONP to a CORS setup.
( s.async && jQuery.inArray( "json", s.dataTypes ) < 0 )
)
);
}
We should document it.
I recently revisited an older discussion, starting from https://github.com/jquery/api.jquery.com/issues/1207#issuecomment-1274554752, where we talked about the callback parameter (script/data) that can be undefined in certain cases. At the time, I suggested that this might need further clarification in the documentation.
Given that <script> tags will now be used for most async requests, it seems this behavior will occur more frequently. Would it be worth updating the documentation to specify when this parameter might be undefined and how developers should handle it?
@vlakoff that's a good point. Would you like to submit a PR with a proposed wording? Please tag me on it if you do.
As for a workaround, I think we could document setting headers without setting scriptAttrs will make the request use XHR and script / data will be present. If we do so, we should also add tests ensuring that, perhaps just after this test on main:
https://github.com/jquery/jquery/blob/0ef6020295b670ad91fba530c854f863faa97a90/test/unit/ajax.js#L101C30-L101C58
It'd be good to also have the same test added for the 3.x-stable branch; I'd also backport the "headers for script transport" one mentioned above from main to 3.x-stable.