How to remove Contact Form 7 JS and CSS, when it’s not needed?

I use Contact Form 7 on all of my sites. Maybe there are better contact form plugins but it’s a habit of mine.

Anyway, Contact Form 7 also has some bad habits and one of those is that inserts its .js and .CSS code on every post or page. It is a weird thing to do, since why would you load those resources on for example this page?

Here is a simple snippet from Stack Overflow that enqueues Contact Form 7 JavaScript and CSS code only if the shortcode is used inside the post. Just add it to your theme function.php file.

function rjs_lwp_contactform_css_js() {
    global $post;
    if( is_a( $post, 'WP_Post' ) && has_shortcode( $post->post_content, 'contact-form-7') ) {
         wp_enqueue_script('contact-form-7');
         wp_enqueue_style('contact-form-7');

    }else{
        wp_dequeue_script( 'contact-form-7' );
        wp_dequeue_style( 'contact-form-7' );
    }
}
add_action( 'wp_enqueue_scripts', 'rjs_lwp_contactform_css_js');

Someone else packed this snippet into a plugin (if you prefer it that way). The advantage is that your code will not get overwritten when you update your theme.

And yes this will remove the Google PageSpeed notice you get related to your Contact Form 7 styles and scripts.

Similar Posts