How does the script_loader_tag function works?

Viewed 3659

I have seen script_loader_tag function applied in functions.php, WordPress, but I struggle to understand completely how does it work.

For example, I've seen examples like this:

function add_async_defer($tag, $handle) {

    if('googlemaps' !== $handle) {
        return $tag;
    }
    return str_replace(' src', 'async="async" defer="defer" src', $tag);
}
add_filter('script_loader_tag', 'add_async_defer', 10, 2);

and it is used to generate the script tag for Google Maps API:

<script type='text/javascript'async="async" defer="defer" src='https://maps.googleapis.com/maps/api/js?key=AIzaSyBz02VRxO_dgaKsBS62TLL6AW4McNTQiKU&#048;callback=initMap&#038;ver=5.2.1'></script>

But what does the $tag and $handle parameters mean?

What does numbers 10 and 2 mean in the end of the add_filter?

Can this function be modified to display the tag conditionally only in the specific pages?

2 Answers

The parameters are as defined below:

$tag: The tag for the enqueued script.

$handle: The script's registered handle. For example the jQuery enqueued by WordPress has the handle 'jquery'

The numeric 10 represents the priority of the callback function in WordPress queue to process all the functions hooked on the script_loader_tag hook.

The numeric 2 represents the number of parameters allowed in callback function.

@chinLeung answered with reference as well.


Considering your code example the following should explain things further:

function add_async_defer($tag, $handle, $src) {
    if('googlemaps' !== $handle) {//Here we check if our handle is googlemaps
        return $tag; //We return the entire <script> tag as is without modifications.
    }
    return "<script type='text/javascript' async='async' defer='defer' src='".$src."'></script>";//Usually the value in $tag variable looks similar to this script tag but without the async and defer
}
add_filter('script_loader_tag', 'add_async_defer', 10, 3);

The $handle is the name you've given to the script when you use wp_enqueue_script.

The $tag is the script tag that is going to be rendered in the DOM.

The 10 is the priority of your filter. Changing to a higher number would make the filter executed later in the process.

And finally the 2 is the number of arguments that the callback is accepting. In your case, it's 2 as there is $tag and $handle.

For more information:

Related