Skip to content

Commit 2a5fa01

Browse files
committed
Fix a bug when multiple calls to update_script_tag() could cause attributes to be added multiple times
1 parent 7046aa0 commit 2a5fa01

File tree

2 files changed

+23
-8
lines changed

2 files changed

+23
-8
lines changed

CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
# Script Loader Tags
22

3+
## 1.2.1 - 2023-02-09
4+
5+
- Fixed a bug when multiple calls to `update_script_tag()` could cause attributes to be added multiple times.
6+
37
## 1.2.0 - 2020-01-15
48

59
- Added possibility for `nomodule` and `type="module"` attributes.

lib/functions.php

Lines changed: 19 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -14,36 +14,47 @@ function update_script_tag( $handle = [], $add = [] ) {
1414
$handle = (array) $handle;
1515
$add = (array) $add;
1616

17-
$additions = '';
17+
$attributes = [];
1818

1919
foreach ( $add as $type ) {
2020
switch ( $type ) {
2121
case 'async':
22-
$additions .= ' async';
22+
$attributes[] = 'async';
2323
break;
2424
case 'defer':
25-
$additions .= ' defer';
25+
$attributes[] = 'defer';
2626
break;
2727
case 'module':
28-
$additions .= ' type="module"';
28+
$attributes[] = 'type="module"';
2929
break;
3030
case 'nomodule':
31-
$additions .= ' nomodule';
31+
$attributes[] = 'nomodule';
3232
break;
3333
}
3434
}
3535

36-
if ( empty( $additions ) ) {
36+
if ( empty( $attributes ) ) {
3737
return;
3838
}
3939

40-
$filter = function( $tag, $current_handle ) use ( $handle, $additions ) {
40+
$filter = function( $tag, $current_handle ) use ( $handle, $attributes ) {
4141
// Bailout if the handle does not apply.
4242
if ( ! in_array( $current_handle, $handle, true ) ) {
4343
return $tag;
4444
}
4545

46-
return str_replace( ' src', sprintf( ' %s src', trim( $additions ) ), $tag );
46+
// Remove existing attributes from attributes array if they are already set on a tag.
47+
foreach ( $attributes as $key => $attribute ) {
48+
if ( preg_match( "/\s{$attribute}[\s>]/", $tag ) ) {
49+
unset( $attributes[ $key ] );
50+
}
51+
}
52+
53+
if ( empty( $attributes ) ) {
54+
return $tag;
55+
}
56+
57+
return str_replace( ' src', sprintf( ' %s src', join( ' ', $attributes ) ), $tag );
4758
};
4859

4960
add_filter( 'script_loader_tag', $filter, 10, 2 );

0 commit comments

Comments
 (0)