You don't need me explaining you how important it is to defer scripts for performance. If your application doesn't need render-blocking scripts you should simply defer them.
Most of the WordPress blogs/sites do not need render blocking scripts, for toggling menu visibility, swapping emojis for SVG's, embed media... All these can be deferred no problem.
The script below will handle all non-Dashboard (WordPress admin) scripts as defer.
You might want to have an allow-list array using the $handle
param. In my case I want everything, to speed up the page render time as much as possible.
/*
* Add defer attribute to enqueued scripts
*
* @param string $tag
* @param string $handle
* @param string $src
* @return void
*/
function defer_scripts( $tag, $handle, $src ) {
if (is_admin()) return $tag;
return '<script type="text/javascript" src="' . $src . '" defer="defer"></script>';
}
add_filter( 'script_loader_tag', 'defer_scripts', 10, 3 );
Code language: PHP (php)