Script Loader Tag using WordPress

This little tidbit I consider a golden nugget for those looking to optimize their website’s page speed. I ran into a situation recently (actually times) where I needed to defer some scripts down to the footer area. If you’ve been developing a while now, you know about render blocking scripts. Put simply, we want our DOM to load first before any scripts are executed.

So there are two wordpress hooks you’re probably familiar with – they’re mentioned below.

For CSS, we can utilize the functions below:

wp_enqueue_style();
wp_register_style();

And for scripts:

wp_enqueue_script

That’s all good and dandy, but what about if we want to add script and/or css properties? To add those extra properties we will need to utilize yet another WordPress function I didn’t even know existed.

This may be useful when you’re looking to add extra properties/attributes to your script tag. Some examples could be:

defer

<script src="defer-script.js" defer</script>

async

<script src="async-script.js" async</script>

crossorigin

We see this used most often when calling files from a remote server ie. bootstrap, icons, libraries.


<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.0/css/all.css" integrity="sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ" crossorigin="anonymous">

script_loader_tag Usage

Alright now that we’ve got that squared away, we can dive into the function itself. Implementation quite similar to WordPress’s family of functions – first define the function. In our case, let’s call our function my_defer_scripts

Next, we want to define an array listing our scripts – let’s name it $defer_scripts

The return value is what’s most important – this is where we add the property. The working script below illustrates how straightforward this is.

Finally, we pass our defined function onto WordPress’ filter function and voila – we’ve got the defer property added to our script tag.


function my_defer_scripts($tag, $handle, $source) {

    $defer_scripts = array( 'some-script', 'another-script' );

if(in_array($handle, $async_scripts)) {
    return '<script type="text/javascript" src=' . $src . ' defer></script>';
}

    return $tag;
}
add_filter( 'script_loader_tag', 'my_defer_scripts', 10, 3 );