Prevent loading unnecessary scripts and styles in WordPress
Some plugins, when installed, add about 2 or 3 scripts and stylesheets to every page on your website. This isn’t necessarily a problem but it would be nice to have scripts loaded only on pages that actually need them.
Let’s take the popular Contact Form 7 plugin as an example. Most likely, only pages that contain the [contact-form-7]
shortcode will need the extra scripts and styles.
The following snippet will check your post content to see if it contains the contact form 7 shortcode. If it doesn’t, it will dequeue the styles and scripts so they will not be loaded.
function dvk_dequeue_scripts() { $load_scripts = false; if( is_singular() ) { $post = get_post(); if( has_shortcode($post->post_content, 'contact-form-7') ) { $load_scripts = true; } } if( ! $load_scripts ) { wp_dequeue_script( 'contact-form-7' ); wp_dequeue_style( 'contact-form-7' ); } } add_action( 'wp_enqueue_scripts', 'dvk_dequeue_scripts', 99 );
You can, of course, add more logic to the function to detect the necessity of scripts for other plugins as well. You will need to know the handles used to identify the scripts and styles of the plugin and the shortcode.
Be careful when implementing this though. If you’re rendering a contact form using a widget or template function (for example), the snippet above won’t detect it and will still dequeue the scripts and styles.
Extra
If you’re a plugin author, register your scripts as soon as possible but only enqueue them from your main display function (the shortcode callback, rendering function, etc..) with the parameter $in_footer
set to true. This way, your scripts will only be loaded when they are actually needed. By registering the script early, users still get a chance to register their own version of it, should they want to.
Some plugins such as PageNavi provide an option to load the bundled stylesheet/script. In the case of PageNavi the stylesheet is small and could be integrated into the theme stylesheet, eliminating a file request.
In the case of WPCF7, there are wp-config.php constants that can be used. For example:
define(‘WPCF7_LOAD_CSS’, false);
Will prevent the loading of the included stylsheet. Again, removes a file request, and such styling may be better done by the theme for better integration.