Automatically Add Defer or ASYNC to all JS files (no matter where they are located)

I’m looking for a way to automatically add defer to all JS files on my server. While I found a way that seem to be working, I am not sure if this is the best way / best practice 2021 for WordPress?

I am running a test environment on XAMPP with PHP 7.4.x and the latest WordPress (5.7.2). I have debug turned on in wp-config and while I am not receiving any errors or notices, I am again, not sure this is the best way / best practice to do this.

Can someone please review and advise?

I am using this code:

add_filter( 'clean_url', 'auto_defer_all_js_and_jquery', 11, 1 );
function auto_defer_all_js_and_jquery( $url ) {

    if ( false === strpos($url, '.js') ) {

        return $url;
    }

    if ( !false === strpos($url, '.js') ) {

        return "$url' defer='defer";
    }
}

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Here’s a solution to your question. This doesn’t take into account the merit of whether or not you should add async or defer to certain assets, it just gives you the tools to do it yourself, or not.

Points to note:

  • this is only for use with Javascript includes (obviously)
  • It’s not 100% accurate because of the method of replacing the tag text, but for 99.9% of the javascript includes you’ll have, it’ll do the job the fine.
  • there is the option to specify which includes should have the async and defer tags, simply add the handles of the assets you want to apply it to. I’ve included JQuery for starters.
  • this code add both defer="defer" and async. Simply delete either of the appropriate if blocks if that’s not what you want.
function add_async_to_js( $includeTag, $handle ) {

    $handlesToChange = [
        'jquery'
    ];

    if ( in_array( $handle, $handlesToChange ) ) {
        if ( strpos( $includeTag, ' defer=' ) === false ) {
            $includeTag = str_replace( ' src=', ' defer="defer" src=', $includeTag );
        }
        if ( strpos( $includeTag, ' async' ) === false ) {
            $includeTag = str_replace( ' src=', ' async src=', $includeTag );
        }
    }
    return $includeTag;
}

add_filter( 'script_loader_tag', 'add_async_to_js', 10, 2 );


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x