apply_filters( ‘script_loader_tag’, string $tag, string $handle, string $src )

Filters the HTML script tag of an enqueued script.

Parameters

$tagstring
The <script> tag for the enqueued script.
$handlestring
The script’s registered handle.
$srcstring
The script’s source URL.

Source

$tag = apply_filters( 'script_loader_tag', $tag, $handle, $src );

Changelog

VersionDescription
4.1.0Introduced.

User Contributed Notes

  1. Skip to note 3 content

    Useful when a script excecution depends on “ attributes, eg:

    add_filter( 'script_loader_tag', 'add_id_to_script', 10, 3 );
    
    function add_id_to_script( $tag, $handle, $src ) {
        if ( 'dropbox.js' === $handle ) {
            $tag = '<script type="text/javascript" src="' . esc_url( $src ) . '" id="dropboxjs" data-app-key="MY_APP_KEY"></script>';
        }
    
        return $tag;
    }
  2. Skip to note 4 content

    It can be used to defer or async all JS scripts :

    function prefix_defer_js( $html ) {
        if ( ! is_admin() ) {
            $html = str_replace( '></script>', ' defer></script>', $html );
        }
        return $html;
    }
    add_filter( 'script_loader_tag', 'prefix_defer_js' );

    You can also use the $handle argument to filter scripts.

You must log in before being able to contribute a note or feedback.