Skip to content

Commit 1f4375a

Browse files
committed
Ajax: Allow custom attributes when script transport is used
Fixes jquerygh-3028 Ref jquerygh-2612 Useful, for example, to add `nonce`, `integrity`, or `crossorigin`.
1 parent 29e76e2 commit 1f4375a

File tree

2 files changed

+26
-3
lines changed

2 files changed

+26
-3
lines changed

src/ajax/script.js

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -43,15 +43,15 @@ jQuery.ajaxPrefilter( "script", function( s ) {
4343
// Bind script tag hack transport
4444
jQuery.ajaxTransport( "script", function( s ) {
4545

46-
// This transport only deals with cross domain requests
47-
if ( s.crossDomain ) {
46+
// This transport only deals with cross domain or forced-by-attrs requests
47+
if ( s.crossDomain || s.scriptAttrs ) {
4848
var script, callback;
4949
return {
5050
send: function( _, complete ) {
5151
script = jQuery( "<script>" ).prop( {
5252
charset: s.scriptCharset,
5353
src: s.url
54-
} ).on(
54+
} ).attr( s.scriptAttrs || {} ).on(
5555
"load error",
5656
callback = function( evt ) {
5757
script.remove();

test/unit/ajax.js

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,29 @@ QUnit.module( "ajax", {
8989
}
9090
);
9191

92+
ajaxTest( "jQuery.ajax() - custom attributes for script tag", 4,
93+
function( assert ) {
94+
var nonceValue = "0123456789";
95+
return {
96+
create: function( options ) {
97+
var xhr;
98+
options.dataType = "script";
99+
options.scriptAttrs = { id: "jquery-ajax-test", nonce: nonceValue };
100+
xhr = jQuery.ajax( url( "data/script.php?header=ecma" ), options );
101+
// Ensure the script tag has the nonce attr on it
102+
assert.ok( nonceValue === jQuery( "#jquery-ajax-test" ).attr( "nonce" ), "nonce value" );
103+
return xhr;
104+
},
105+
success: function() {
106+
assert.ok( true, "success" );
107+
},
108+
complete: function() {
109+
assert.ok( true, "complete" );
110+
}
111+
};
112+
}
113+
);
114+
92115
ajaxTest( "jQuery.ajax() - do not execute js (crossOrigin)", 2, function( assert ) {
93116
return {
94117
create: function( options ) {

0 commit comments

Comments
 (0)