script_loader_tag
Allows you to change the HTML of a <script> tag enqueued for output by wp_enqueue_script().
Usage
add_filter( 'script_loader_tag', 'wp_kama_script_loader_tag_filter', 10, 3 );
/**
* Function for `script_loader_tag` filter-hook.
*
* @param string $tag The `<script>` tag for the enqueued script.
* @param string $handle The script's registered handle.
* @param string $src The script's source URL.
*
* @return string
*/
function wp_kama_script_loader_tag_filter( $tag, $handle, $src ){
// filter...
return $tag;
}
- $tag(string)
- HTML of the
<script>tag. - $handle(string)
- Script name (handle), specified as the first parameter of wp_enqueue_script().
- $src(string)
- Script URL.
Examples
#1 Look under the hood of the standard Twenty Sixteen theme
One of the theme's main scripts is enqueued as follows:
wp_enqueue_script( 'twentysixteen-script', get_template_directory_uri() . '/js/functions.js', array( 'jquery' ), '20160816', true );
In this case, variables containing the following data are passed to the filter:
$tag = <script type='text/javascript' src='http://wp-test.com/wp-content/themes/twentysixteen/js/functions.js?ver=20160816'></script> $handle = twentysixteen-script $src = http://wp-test.com/wp-content/themes/twentysixteen/js/functions.js?ver=20160816
#2 Another example
The same theme uses a condition through wp_script_add_data():
// Enqueue the script. wp_enqueue_script( 'twentysixteen-html5', get_template_directory_uri() . '/js/html5.js', array(), '3.7.3' ); wp_script_add_data( 'twentysixteen-html5', 'conditional', 'lt IE 9' );
$tag = <!--[if lt IE 9]> <script type='text/javascript' src='http://wp-test.com/wp-content/themes/twentysixteen/js/html5.js?ver=3.7.3'></script> <![endif]--> $handle = twentysixteen-html5 $src = http://wp-test.com/wp-content/themes/twentysixteen/js/html5.js?ver=3.7.3
#3 Add defer or async attributes to a script
This example shows how to add an attribute to an enqueued script. It adds defer, but any other attribute can be used instead.
wp_enqueue_script( 'my-script', get_template_directory_uri() . '/js/my-script.js' );
add_filter( 'script_loader_tag', 'change_my_script', 10, 3 );
function change_my_script( $tag, $handle, $src ) {
if ( 'my-script' === $handle ) {
// return str_replace( ' src', ' async src', $tag );
return str_replace( ' src', ' defer src', $tag );
}
return $tag;
}
Read more about the async and defer attributes here.
See a more complete example here.
#4 Specify that a script is an ES6 module
Read about ES6 modules in this note.
add_filter( 'script_loader_tag', 'scripts_as_es6_modules', 10, 3 );
function scripts_as_es6_modules( $tag, $handle, $src ) {
if ( 'my-script' === $handle ) {
return str_replace( '<script ', '<script type="module"', $tag );
}
return $tag;
}Changelog
| Since 4.1.0 | Introduced. |
Where the hook is called
script_loader_tag
wp-includes/class-wp-scripts.php 496
$tag = apply_filters( 'script_loader_tag', $tag, $handle, $src );