Restricting a Plugin to Only Load its CSS and JS on Selected Pages?

I’d like to cause a plugin to restrict its loading of CSS stylesheets and JavaScript JS files to only those pages for which they are needed.

An example for my question is the plugin Contact Form 7 which I’ve used to create a form in one page on my site (the “contact me” page). However it adds the following lines to EVERY page/post on the website:

Read More
<link rel='stylesheet' id='contact-form-7-css'  href='http://www.r-statistics.com/wp-content/plugins/contact-form-7/styles.css?ver=2.3.1' type='text/css' media='all' /> 

<script type='text/javascript' src='http://www.r-statistics.com/wp-content/plugins/contact-form-7/scripts.js?ver=2.3.1'></script> 

This makes me suspect that this plugin is impairing my site’s loading time, for an extension that interests me on only one page on the site.

Thus, my question is how can I remove these extra lines from all the pages except for the “Contact Me” page but without deactivating the plugin?

Related posts

Leave a Reply

1 comment

  1. Styles and scripts are always set up by the functions wp_enqueue_script() and wp_enqueue_style(), which have to be tied to a particular action hook in order to function. I took a peek inside Contact Form 7, and it looks like it’s using action tags of wpcf7_enqueue_scripts and wpcf7_enqueue_styles to add them to the wp_print_scripts and wp_print_styles hooks.

    So, what you need to do is un-hook the scripts and styles from every page but your contact page. The wp_head action fires before the script and styles actions, so you’ll need to add something like this to your theme’s functions.php file:

    function remove_wpcf7_extras() {
        remove_action('wp_print_scripts', 'wpcf7_enqueue_scripts');
        remove_action('wp_print_styles', 'wpcf7_enqueue_styles');
    }
    
    if( ! is_page('contact me') ) {
        add_action('wp_head', 'remove_wpcf7_extras');
    }
    

    The is_page() function will return true when you’re on the contact page (assuming the name is “contact me”) … you can also use the page slug and page ID for the filter. On all other pages, the if() conditional will add the script/style removal function to the wp_head action, which fires just before the wp_print_scripts and wp_print_styles actions.

    This should remove the extra code from your pages, and you won’t have to deactivate the plug-in or edit any core files. The functions and code I’ve listed above also won’t cause your theme to break if you remove Contact Form 7 in the future, either … so no need to worry about future upgrade compatibility.