
Filter Hook since 4.1.0
script_loader_tag
Filters the final <script> tag markup for an enqueued script
Description
script_loader_tag is how you add async/defer or a nonce to a specific enqueued script without touching the theme's enqueue logic wholesale.
When it runs
During wp_head/wp_footer script printing, once per enqueued script handle.
Signature
apply_filters( 'script_loader_tag', string $tag, string $handle, string $src );Parameters
$tagstring — The <script> tag HTML.$handlestring — The script's registered handle.$srcstring — The script's source URL.
Examples
Basic
add_filter( 'script_loader_tag', function( $tag, $handle ) {
if ( 'my-script' !== $handle ) {
return $tag;
}
return str_replace( ' src', ' defer src', $tag );
}, 10, 2 );Add the defer attribute to one specific enqueued script.
Common Use Cases
- Add async/defer to specific scripts
- Add a nonce or crossorigin attribute
- Remove type="text/javascript" for cleaner markup
Common mistakes
- Deferring a script that other enqueued scripts depend on synchronously — breaks execution order
Related hooks
FAQ
Does script_loader_tag work for scripts I just echo manually?
No — only for scripts registered via wp_enqueue_script()/wp_register_script(). Manually echoed <script> tags aren't touched.
Source: wp-includes/class-wp-scripts.php