Conditionally loading JS & CSS Files in WordPress / WooCommerce sites for Better SEO

The score you get on Google PageSpeed Insight tool is a major factor for your website or e-commerce site's search engine ranking, but if you are on WordPress, especially with WooCommerce it is possible your scores are pretty bad. 


This is a series of WordPress x PageSpeed optimization, this one is just one of many possible methods, each methods contribute towards a better score -- however since every site is different the amount of each technique and the way you implement it might be different. What I am trying to do here is that I am giving you an overview of things that can be done + a few pointers for the kind of code you would be doing. 



Unused JS / CSS 

If you use a theme bought from a marketplace, or running a site with many plugins to handle different functionalities then it is possible your site loads up a lot of JavaScript and CSS files, dozens of it. 

These assets are crucial but when there are too many of it, it quickly becomes a problem. Google doesn't want you to load styles and scripts that makes your site unresponsive during page loads. 

Are you a developer? 

If not and you want to improve your website score then I recommend you to hire a WordPress expert who can understand the implement the code bits in this tutorial to best fit your website (Fun fact: I am a WordPress developer)

Getting rid of plugins that you don't need

Cutting down on plugins and / or theme modules  you use on your site is a very straightforward way to handle this - just go through your WordPress / WooCommerce site, look for plugin that are there and decide what you can remove without compromising much on the features you want on your website. 

Target JS & CSS Files individually, and conditionally

Great thing about WordPress is that it is highly-customizable, using WP hooks and filters. 

What we want to achieve here

If you look at your Google PageSpeed Insight / Lighthouse recommendations and opportunities section you will see it will list out many scripts and CSS file under "Reduce unused JavaScript" and "Reduce unused CSS", and maybe only one big file (if you happen to use a plugin like Autoptimize with default settings)

Step 1 - Prepare for the next steps

If you are using a plugin like Autoptimize then it may be merging all your JS and CSS file in one big file that is cached. If that's the case then you should use the "Exclude.." options in the settings page to exclude the files we want to play around with in the next steps. 

This recommendation is more like a mandatory step, if you don't do this then Autoptimize, or any other optimization plugin will end up serving all of these JS and CSS file in one big file and the code in the next steps won't be able do its job at all.

Step 2 - Make a list of JS and CSS

The files that shows up in the PageSpeed reports, make a list of those, or a mental note of it. Just remember the files that you see so we can take the next steps according to that. 

Step 3 - Decide what can be removed on a page

You do not have to think about each individual page, but the type of page. For e.g if you run a e-commerce site and say your theme loads a product image gallery on the product page you definitely do not need the scripts and CSS for that feature on your home page, or any other type of page other than a product page. 

To keep things simple we will focus on optimizing the homepage in this article. 

Example 1 - Removing CSS only on home page

You have a great website, maybe some contact forms on your website too but if the contact forms are on another page and not the homepage then you are loading the Contact form's JavaScript and CSS for no reason on the homepage, it just ends up becoming an unused resource and that is what Google wants us to fix. 

To fix it we will use this code


/*
Dequeuing CSS files conditionally
*/
function stramaxon_remove_unnecessary_styles() {

	$remove_always = array(
		// an empty array
	);


	// If home
	if ( is_home() || is_front_page() ) {
		$remove_always['amazing-contactform-css'] = 'amazing-contactform'
	}


	// Run the loop
    foreach( $remove_always as $item_script ) {
    	wp_dequeue_style( $item_script );
    	wp_deregister_style( $item_script );
    }
}
add_action( 'wp_print_styles', 'stramaxon_remove_unnecessary_styles', 1 );
This is one way of doing it - you add the 'amazing-contactform' handle to the $remove_always array if the current page a home or the front page. 

Don't get confused by 'amazing-contactform-css' and 'amazing-contactform', the '``-css' at the end in the key of the array item can be anything you want, just the value should always correspond to the handle of the script or style. You can find that by looking into your website's source code using Chrome DevTools. 

Another way of doing it is to always remove the contact form's CSS but only load it on the contact page, we can do it like this

/*
Dequeuing CSS files conditionally
*/
function stramaxon_remove_unnecessary_styles() {

	$remove_always = array(
		'amazing-contactform-css' => 'amazing-contactform',
	);


	// If a page with the slug 'contact-us', then unset the array item
	if ( is_page('contact-us') ) {
		unset($remove_always['amazing-contactform-css']);
	}


	// Run the loop
    foreach( $remove_always as $item_script ) {
    	wp_dequeue_style( $item_script );
    	wp_deregister_style( $item_script );
    }
}
add_action( 'wp_print_styles', 'stramaxon_remove_unnecessary_styles', 1 );
In this method we are adding the handle to the array by default, then we use 'is_page()' function in WordPress to check the page, and if it is a page with the `contact-us` hook we use `unset()` to remove the handle from the array. 

This way `amazing-contactform-css` is removed on all pages but the `contact-us` page. 


What about the JavaScript?

It function we will use is almost identical to the one for CSS. 

/*
Dequeing JS files conditionally
*/
function stramaxon_remove_unnecessary_script() {

	$remove_always = array(
		'amazing-contactform-js' => 'amazing-contactform',
	);


	// If a page with the slug 'contact-us', then unset the array item
	if ( is_page('contact-us') ) {
		unset($remove_always['amazing-contactform-js']);
	}


	// Run the loop
    foreach( $remove_always as $item_script ) {
    	wp_dequeue_script( $item_script );
    	wp_deregister_script( $item_script );
    }
}
add_action( 'wp_print_scripts', 'stramaxon_remove_unnecessary_script', 1 );

If you want to target WooCommerce specific pages then look at the available conditional tags in WooCommerce.

Where to put these PHP code? Use a child theme's functions.php file.

That's it! Now you have to carefully check the scripts and styles load on your website and use the functions above to remove that conditionally on pages. 

Why can't you give me the exact code that works on my website?

That's website each site is different. Unlimited number of theme and plugin's combination in the WordPress ecosystem makes it nearly impossible to give a one-for-all solution. Also since this is a developer level work it is best done by an expert otherwise you may end up breaking your website with custom PHP code. 

You can hire me for the work, email me at depy45631@gmail.com