WordPress – Remove Contact Form 7 CSS and JavaScript If Page Does Not Have Contact Form

Contact form 7 includes its CSS and JavaScript files to all the pages even when there is no contact form on the page. This adds up more load to the page and includes unnecessary files which may conflict with other CSS and JS. It is a good practice to remove these files from all pages except the page with the contact form.

Add below code to your functions.php file or into the plugin’s code to remove Contact form 7 CSS and JS.

<?php
/**
* Remove Contact Form 7 js and css unless on the contact page
**/
add_action( 'wp_enqueue_scripts', 'sr_remove_cf7_scripts' );
function sr_remove_cf7_scripts() {
    if ( !is_page('contact') ) {
        wp_deregister_style( 'contact-form-7' );
        wp_deregister_script( 'contact-form-7' );
    }
}
?>