WordPress plugins provide loads of useful functionality and can really expand the capability of a website. But very often these plugins will load on every page and slow your site down. Today we’ll show you how to only load the plugins you need.
The WordPress plugin library is fantastic. There are thousands of plugins that can instantly improve your website. Very often this comes at a performance cost because the plugin’s resources are loaded on all your website pages.
This is fine, but you only actually need to load the resources for this plugin on pages where the contact form exists. If you load the JS and CSS on every single page then those pages are loading resources they don’t need. This will affect how fast those pages load because each will be an additional HTTP request.
Why Is this So Important?
There’s two reasons; your users and Google. A slower website isn’t going to convert as well as a fast one, and page speed is a confirmed Google ranking signal.
In fact if you run your website through the Google Pagespeed Insights Tool, it will actually report on any render blocking resources such as a plugin’s CSS and JS.
There are some approaches to combat this such as loading resources asynchronously or moving them to the bottom of the DOM.
But wouldn’t it be great to not load them all if they’re not needed, that sounds much smarter.
First of I’ll add the caveat that this is probably not the only way to achieve the aim here and it may not be the most effective, but I’ve found that it works for me.
To only load a WordPress plugin when we need it, we can make use of the WordPress wp_deregister_script function. We can use this to create a function that deregisters scripts and styles on specific pages.
We combine this with a conditional IF statement that only fires the function on selected pages. Say for example we only want to load our contact form plugin on our contact page. To do this we write an IF statement that checks if the page is NOT our contact page, and if so deregisters the contact form plugin.
To do this we need two bits of information; the ID for the page we want the plugin to be loaded on, and the handle for the plugin.
Obviously replace ‘123’ with the ID of the page where you want the plugin to load, and replace ‘contact-plugin’ with the handle for the plugin you’re trying to control.
We then hook into the WordPress ‘wp_print_scripts’ and ‘wp_print_scripts’ actions to fire our function. Add this snippet into your functions.php file for it to take effect.
As always, be very careful when editing your functions.php file. Test it locally first, and if you’re not comfortable then ask a professional to do it.