Defer parsing of JavaScript in WordPress

I was working on a website and today I tried to check it’s GTMetrics score. It showed me that the website needs to defer it’s js files so that they don’t block other contents from loading. I used this small code snippet to do it in WordPress. Thought  I’d share with you guys.

function defer_js_parsing($url){
    if ( FALSE === strpos( $url, '.js' ) ) return $url;
    if ( strpos( $url, 'jquery.js' ) ) return $url;
    return "$url' defer ";
}

add_filter( 'clean_url', 'defer_js_parsing', 10, 1 );

If you need any help understanding the code please let me know in the comment. Thanks a lot.

Leave a Reply

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