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

Home » WordPress Tutorials » How To Add Defer & Async Attributes To Scripts Without A Plugin
  • add defer and async attributes to scripts without a plugin

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 is 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 file name 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.

By | 2018-06-13T09:45:27+00:00 June 13th, 2018|Categories: WordPress Tutorials|0 Comments

About the Author:

Scott Hartley is a WordPress Developer who focuses on website performance optimization, SEO, and security. He can't tell you what a color wheel is but he knows the intricacies of making a website load quickly.

Leave A Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.