Defer parsing of JavaScript [duplicate]

You have to be careful with PageSpeed and GTMetrix and other such tools because the provide results without context. They have pre-set rules like ‘scripts should be deferred and/or loaded at the end of the page above the closing </body> tag. But some scripts can’t be deferred if you want them to provide the functionality they were intended to provide and some have to load in the header (Facebook’s scripts do this, LinkedIn too). So they’re great tools to test and check and get a sense of where you could make improvements, but that doesn’t mean they’re always 100% correct in what they’re telling you to do.

That said, here’s what I use on sites to add a defer tag to scripts that are being loaded.

function addaprefix_defer_js( $url ) {
    if ( is_user_logged_in() ) return $url;
    if ( FALSE === strpos( $url, '.js' ) ) return $url;
    //you'll want to add a list of scripts here that you do NOT want to defer, jquery.js is definately one of them
    if ( strpos( $url, 'jquery.js' ) ) return $url; 
    return str_replace( ' src', ' defer src', $url );
}
add_filter( 'script_loader_tag', 'addaprefix_defer_js', 10 );

Where I have addaprefix_ change that to whatever you want/need the prefix of your functions to be.