Defer CSS & JavaScript manually with code in function.php

Follow the steps below to defer CSS & JavaScript and fix render blocking problem easily with code. Here if you want to do that with a plugin.

Add the code below into function.php at the end. This code will show all JavaScripts that load in the header and in the footer. After you finish with deferring the Javascript remove the code above from function.php

add_action( 'wp_head', 'show_scripts_in_header', 9999 );
add_action( 'wp_footer', 'show_scripts_in_footer', 9999 );
// JavaScripts appear on the top, before the headerfunction 
global $wp_scripts;echo '<pre>'; 
print_r($wp_scripts->done); echo '</pre>';
// JavaScripts appear on the bottom, after the footerfunction 
global $wp_scripts;echo '<pre>';
print_r($wp_scripts->done); echo '</pre>';

You will get something like this:Header:show all JavaScripts that load in the headerFooter: Choose which JavaScript file you want to defer with the following code:

add_filter( 'script_loader_tag', 'defer_scripts_myhostingfacts', 10, 3 );
function defer_scripts_myhostingfacts( $tag, $handle, $src ) {
// The handles of the enqueued scripts we want to defer
$defer_scripts = array('here', 'is', 'an', 'example', 'change', 
'actual-example', 'vc_woocommerce-add-to-cart-js');
if ( in_array( $handle, $defer_scripts ) ) {
return '<script src="' . $src . '" defer="defer" type="text/javascript"></script>' . "\n";}
return $tag;

jQuery is best to load in the head because a lot of plugins and themes need jQuery to load before loading some styles, front-end animations or some validation etc…

//The code below remove the scripts from head and add them in footer

function remove_head_scripts() {
remove_action(‘wp_head’, ‘wp_print_scripts’);
remove_action(‘wp_head’, ‘wp_print_head_scripts’, 9);
remove_action(‘wp_head’, ‘wp_enqueue_scripts’, 1);

add_action(‘wp_footer’, ‘wp_print_scripts’, 5);
add_action(‘wp_footer’, ‘wp_enqueue_scripts’, 5);
add_action(‘wp_footer’, ‘wp_print_head_scripts’, 5);
add_action( ‘wp_enqueue_scripts’, ‘remove_head_scripts’ );
//Test thoroughly if everything works


Share on facebook
Share on twitter
Share on pinterest
Share on linkedin

Leave A Comment

Covid-19 coronavirus SiteGround discount STAY HOME STAY SAFE!!!

WP Rocket - WordPress best caching plugin defer CSS & JavaScript fix render blocking WordPress

Related Posts