Conditionally Loading Scripts and Styles for WordPress Plugins

There are many plugins that tend to automatically add their JS and CSS files to all posts and pages of your blog even though you might be using the plugin's functionality only on one or two pages.

For instance, a gallery plugin. You might have the gallery only on one page of your site, yet the plugin loads the required JS and CSS files on all pages. This is counter-productive and can negatively effect your site's performance and page load speeds.

The good thing is that you can easily prevent this from happening by restricting a plugin's scripts and styles only to specific posts and pages using the wp_dequeue_script and wp_dequeue_style functions. Here's how.

1: Finding the Plugin Handles

The first step is to find the unique handles of plugins that you want to restrict.

You can do this by digging into the plugin files, but that can be a time consuming and frustrating thing to do.

Instead here's a simple workaround:

Step 1: Open your theme's functions.php file and add the following function to the end of the file.

# Finding handle for your plugins 
function display_script_handles() {
    global $wp_scripts;
	if(current_user_can('manage_options') && is_admin()){ # Only load when user is admin
	foreach( $wp_scripts->queue as $handle ) :
         $obj = $wp_scripts->registered [$handle];
         echo $filename = $obj->src;
		 echo ' : <b>Handle for this script is:</b> <span style="color:green"> '.$handle.'</span><br/><br/>';
	endforeach;
	}	
}
add_action( 'wp_print_scripts', 'display_script_handles' );

Note that this function will output the script source followed by the handle, to the top of your webpage, for all scripts that are enqueued using the wp_enqueue_scripts function.This will only work when you are logged in as admin. So regular site visitors will not be able to see this.

Step 2: Once you have added the function and saved your functions.php file, visit any single post page of your site (while you are still logged in as an admin). You should now be able to see the source of all scripts that have been enqueued to load along with the handles on the very top of the page as shown in the image below:

Wordpress plugin handles

As mentioned earlier, regular site visitors will not be able to see this.

Note: Remove this function from your functions.php page once you are done noting down the handles for your plugins.

2: Restricting Scripts and Styles to Specific Posts and Pages

Now that we have the plugin handles, we can easily prevent these plugins from loading CSS and JS files on all pages and restrict them only to pages that we want by using the wp_dequeue_script() and wp_dequeue_style() functions as follows:

wp_dequeue_script('script-handle');
wp_dequeue_style('script-handle'); 

Let's look at a working example to see this in action.

Example: Let's take the contact form 7 plugin. This plugin loads its JS and CSS files on all posts and pages of your site even though you might be adding the contact form only on one or two pages.

To restrict this plugin, we first start by finding the plugin's handle which is contact-form-7. Now let's say we want to allow the plugin to load it scripts and styles on all pages of your site but not the posts. We can achieve this by adding the following function to your theme's functions.php page.

# Restrict scripts and styles
function conditionally_load_plugin_js_css(){
if(! is_page() ) { # Only load CSS and JS on Pages but not on Posts		
	wp_dequeue_script('contact-form-7'); # Restrict scripts.
	wp_dequeue_style('contact-form-7'); # Restrict css.		
	}
}	
add_action( 'wp_enqueue_scripts', 'conditionally_load_plugin_js_css' ); 

To be even more specific, let's say you have the contact form on two pages on your site and the Id of these pages are 4 and 12. You can restrict the plugin to only these two pages by adding a comma separated list of IDs in an array to the is_page() function as follows:

function conditionally_load_plugin_js_css(){
if(! is_page( array(4,12) ) ){	# Load CSS and JS only on Pages with ID 4 and 12	
    wp_dequeue_script('contact-form-7'); # Restrict scripts.
    wp_dequeue_style('contact-form-7'); # Restrict css.		
    }
}	
add_action( 'wp_enqueue_scripts', 'conditionally_load_plugin_js_css' );

In a similar way, you can restrict the JS and CSS to specific single posts, by using a comma separated list of single post IDs as follows:

 if(! is_single( array(12,14,22) ) ) # Load CSS and JS only on Single Posts with ID 12, 14 and 22.

If you want to restrict the plugin to posts with ID's 5 and 6 and Pages with ID 12 and 14, you can use the following:

 if(! is_single( array(5,6) ) && ! is_page( array(12,14) ) ) 
Note: To get ID of a post or page, open the post/page for editing in your wordpress dashboard. You will now be able to see the ID number in the URL. (eg: post=145 or page=45)

This way, you can couple several if statements with several wp_dequeue_script and wp_dequeue_style functions to restrict scripts and styles from various plugins to specific posts and pages.

Note: make sure to add this function to the end of your functions.php page or after the wp_enqueue_scripts() function.

Restricting plugins this way can reduce HTTP requests and help speed up your page loads which will in-turn save bandwidth and improve site rankings. You can also use async and defer attribute to prevent render blocking javascript from slowing down your page load times. Check out this article to know how you can add the defer or async attribute to your script tags.

 
 
 
 

Comments

  1. Love that way of finding script handles to de queue!

  2. MattT says:

    Great documentation and process.

    IF(?) I read it all correctly, your script 1) identifies specific class/code/postID/pageID/ then 2) Turns OFF those scripts for those class/code/postID/pageID.

    I have need to restrict scripts to specific pages, thereby turning OFF for ALL but those specified. Wouldn't that require some sort of call to NOT turn OFF for those class/code/postID/pageID.

    Maybe I read it wrong?

  3. MattT says:

    answered my own question - that's what the "!" does :) thanks for this great reference!

  4. John says:

    Many thanks for this great tutorial; I have spent the day trying lots of others and this one worked AND explained matters clearly. I have tweeted and Google+ shared.

  5. pmwarman says:

    What if i have multiple plugins to block. what changes need in script?

  6. Martin says:

    Excellent post, well written and easy to understand. Quickly fixed an issue I've been struggling with for ages, thanks!!

  7. What about enqueued styles ?

  8. Ankit Nawlakha says:

    All I can see is handle for this script is : $handle
    What does that mean?

  9. D Boy says:

    What about the handlers for enqueued styles?

  10. Joey says:

    Thanks for the tutorial! This is the best version I've found online, and I've finally achieved what I wanted to do. As for the handlers for enqueued styles, somehow they didn't come up by following the above (like other comments say), but found a resource mentioning it (goo.gl/SpqFkT).

    • M Mukesh says:

      Thank you Joey, I am glad you found it useful. As for the handlers, I rechecked the code and it seems to be working fine for me. Note that the code only works when you are logged in as the site admin.

  11. I have seen that this method doesn´t work with old plugins. I´m trying with Bookshelf slider
    https://codecanyon.net/item/multipurpose-bookshelf-slider-wordpress-plugin/2228996

  12. Manish says:

    Best content. For the new blogger.

  13. jeff says:

    The line that says:
    if(current_user_can('manage_options') && ! is_admin()) {
    actually does NOT allow admins to see this information.

    The IF statement says that the user must have manage_options ability but must NOT be an admin.

    So it should be either this:
    if( is_admin() ){

    Or this:
    if( current_user_can('manage_options') ){

  14. jeff says:

    This script only shows Javascript that is queued and does not list any style css at all.

    Thanks

    • M Mukesh says:

      Jeff, every plugin has a unique 'handle'. The first script helps you identify this handle. Once the handle is identified, you can then block the plugin from loading Javscript as well as CSS using the wp_dequeue_script() and wp_dequeue_style() functions.

Leave a Reply

Your email address will not be published. Required fields are marked *