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";
}
}