How To Add Defer & Async Attributes To Scripts Without A Plugin

Whether you’re designing a plugin or theme, or simply a website owner who wants to improve your website performance, adding defer and async attributes to scripts are imperative.

While this feature was added to WordPress core, it’s still not used or mainstreamed into most themes and plugins.  This is a shame because the script loader tag can greatly improve your website’s performance when used effectively.

The best part is it can be used for any script that is enqueued on your website. This is regardless of whether it’s in a plugin or apart of your theme.

While there are plugins that can do this, this method allows you to have more granular control. It can be used in your themes and plugins inherently to make your user’s websites load faster.

Example Code.

add_filter( 'script_loader_tag', function ( $tag, $handle ) {
    if ( 'contact-form-7' !== $handle )
        return $tag;

    return str_replace( ' src', ' defer="defer" src', $tag );
}, 10, 2 );

The above code uses an example script handle from Contact Form 7.  You can easily expand this but to add scripts you need to get the script handle (for themes this is the handle you used when registering the file and used to enqueue it). If you are a user, you can install various plugins that can help you find this such as:

Once you located it, adding the above code for multiple files is pretty straightforward.

add_filter( 'script_loader_tag', function ( $tag, $handle ) {
    if ( 'contact-form-7' || 'some-js-file' !== $handle )
        return $tag;

    return str_replace( ' src', ' defer="defer" src', $tag );
}, 10, 2 );

Essentially all you need to do is the following:

  1. Add the ||.
  2. Make your filename wrapped in ‘ ‘.

This code can be added in your functions.php file, child theme, or site-specific kitchen sink plugin.

You can do this for all the JS files you would like. It will only affect the files that you specify. This allows you to control exactly what you defer or async. Additionally, the above code is only for adding the defer attribute. If you wanted to change that to async you only need to change the part where it says defer=”defer” to async=”async” however defer is recommended for performance reasons.

scott hartley

About the author

Scott is a web performance geek, lover of all things coffee, and avid video game player. His WordPress work delves into web performance, web security, and SEO.

Leave a Comment