The Easiest Way to Defer Scripts in WordPress Ever!!

Deferring Scripts in WordPress is not the easiest thing to do. Many plugins add scripts to your site, and can become a mess very quickly and easily. Deferring one script at a time is not very efficient. Because of this, I wrote a short function that takes the hassle of deferring scripts.

// add defer to all scripts
add_filter('script_loader_tag', 'defer_scripts', 10, 2);
function defer_scripts( $tag ) {
	$scripts_to_ignore = array('jquery.js');
	$scripts_to_async  = array('bootstrap.min.js');

	if     ( count( array_filter($scripts_to_ignore, create_function('$e','return strpos("'.$tag.'", $e);') ) )>0 )
		return $tag;
	elseif ( count( array_filter($scripts_to_async,  create_function('$e','return strpos("'.$tag.'", $e);') ) )>0 )
		return str_replace( ' src', ' async src', $tag );
	else
		return str_replace( ' src', ' defer src', $tag );
}

The function works easily. Simply copy this function into your functions.php file, and will add a defer tag to all scripts. I created two arrays in the function, scripts_to_ignore and scripts_to_async. The first one is to leave scripts to load in line. I added this to help eliminate any errors, so add any scripts that need to load first to avoid breaking functionality. The second one is to use an async tag instead. Add all scripts that do not have any dependencies or if all their dependencies are in the scripts to ignore array to the async array. These will load any time.

**Only works in WordPress 4.1+

Leave a comment

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