This website uses cookies to allow us to see how the site is used. If you continue to use this site, we assume that you are okay with this. If you want to use the sites without cookies, please see our privacy policy.

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.

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.