Code Optimisation - Disable scripts and styles of plugins
Many plugins and themes add JavaScript and CSS files to your site and usually these plugins will increase the total size of the page, the number of HTTP request in order to load each file separately.
The good news is that WordPress has a built-in system that allows us to deregister these scripts and styles.
Well, it doesn’t mean that we won’t use these scripts and styles, we just use it in a different way: Combine multiple files into single files.
For example, we’ll put all plugin styles into one single file, lets say: plugin.css and all plugin scripts into ‘plugin.js‘.
In order to figure out what scripts or styles you want to disable, you might have to get your hands dirty. This means looking in code. But the dirt truth is that not all plugin authors are using wp_enqueue_script() and wp_enqueue_style() correctly, then please encourage them to do so. It allows the rest of us to work with their code using the methods WordPress provides.
Disable JavaScript
Take contact form 7 as our exercise.
Open the wp-contact-form-7.php
file in your favorite text editor and do a search for wp_enqueue_script
. You’ll find this bit of code:
[php]
wp_enqueue_script( ‘contact-form-7’, wpcf7_plugin_url( ‘contact-form-7.js’ ), array(‘jquery’, ‘jquery-form’), WPCF7_VERSION, $in_footer );
[/php]
Open your theme’s functions.php file and add this PHP in:
[php]
add_action( ‘wp_print_scripts’, ‘my_deregister_javascript’, 100 );
function my_deregister_javascript() {
wp_deregister_script( ‘contact-form-7’ );
}
[/php]
Once saved, the script will no longer load. You can deregister as many scripts as you want within this function.
Disable styles
Take WP-PageNavi as our exercise.
First open wp-pagenavi.php in a text editor and search for wp_enqueue_style. you’ll find:
[php]
wp_enqueue_style(‘wp-pagenavi’, get_stylesheet_directory_uri().’/pagenavi-css.css’, false, ‘2.50’, ‘all’);
[/php]
and
[php]
wp_enqueue_style(‘wp-pagenavi’, plugins_url(‘wp-pagenavi/pagenavi-css.css’), false, ‘2.50’, ‘all’);
[/php]
Then add this to your theme’s functions.php file.
[php]
add_action( ‘wp_print_styles’, ‘my_deregister_styles’, 100 );
function my_deregister_styles() {
wp_deregister_style( ‘wp-pagenavi’ );
}
[/php]
That’ll disable the stylesheet for this plugin. You can deregister as many styles as you want within this function.
The end
You’ve disabled several scripts and styles, but you need to append styles that you’ve disabled to the end of your theme’s style.css file or a new file like plugin.css, and combine the scripts you just disabled into a single file like plugin.js and load it yourself.