How to load WordPress JavaScript asynchronously

avatar
Share This:

By putting the following code in functions.php, you can load WordPress JS asynchronously. Effective if jquery.js or jquery-migrate.min.js appears in “Exclude resources that prevent rendering” in PageSpeed ​​Insights.

if ( !(is_admin() ) ) {
    function replace_scripttag ( $tag ) {
        if ( !preg_match( '/\b(defer|async)\b/', $tag ) ) {
            return str_replace( "type='text/javascript'", 'async', $tag );
        }
        return $tag;
    }
    add_filter( 'script_loader_tag', 'replace_scripttag' );
}

However, if I do this, my PageSpeed ​​Insights score will go up, but the Cocoon blog card image won’t display properly, so I changed it back.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

17 + four =