Improve loading, Remove unnecessary scripts and styles in WordPress

Some of the plugins, when installed, add 2 or 3 scripts and stylesheets to every page on 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 a example of the most popular Contact Form 7 plugin. Most likely, only pages that contain the

 [contact-form-7] 

shortcode will need the extra scripts and styles.

The following code 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 pv_dequeue_scripts() {
    
    $load_scripts = false;

    if( is_singular() ) {
    	$post = get_post();

    	if( strstr($post->post_content, '[contact-form-7 ') ) {
        	$load_scripts = true;
    	}

    }

    if( ! $load_scripts ) {
        wp_dequeue_style( 'contact-form-7' );
        wp_dequeue_script( 'contact-form-7' );
    }

}

add_action( 'wp_enqueue_scripts', 'pv_dequeue_scripts');

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 code above won’t detect it and will still dequeue the scripts and styles.

How To Create A Shortcode

WordPress makes it pretty simple to make your own shortcodes, so let’s create a shortcode for print a “hello” text. Open your function file and copy the below php code and past into function.php file.

function MyShortCode()
{
echo "Hello";
}
add_shortcode('mycode', 'MyShortCode');

Now use the [mycode] for print “hello”