Fix Defer Parsing of JavaScript in WordPress WIthout Any Plugin

Share Now

Add the defer attribute to your JavaScript files without the need for a plugin by adding the following code snippet to your functions.php file:

function defer_parsing_of_js( $url ) {
    if ( is_user_logged_in() ) return $url; //don't break WP Admin
    if ( FALSE === strpos( $url, '.js' ) ) return $url;
    if ( strpos( $url, 'jquery.js' ) ) return $url;
    return str_replace( ' src', ' defer src', $url );
}
add_filter( 'script_loader_tag', 'defer_parsing_of_js', 10 );

Essentially, this snippet tells WordPress to add the defer attribute to all your JavaScript files except jQuery.

*** This works for general WordPress Websites.
If it doesn’t work then use this plugin instead

Async JavaScript

Picture of Nahid Mahamud

Nahid Mahamud

Web Developer | Graphic Designer | WordPress & Woo-commerce Expert