How To Load the Contact Form 7 Script for a Contact Page Only

Contact Form 7 loads its JavaScript and CSS files on every page and this cause load problems in the whole site specialy in the home page with PageSpeed Insights when i notice the CSS and JavaScript and there was no contact form there so what we need to fix this is to remove these js and css from any page who is not contact page that contains the contact form itself

all u need is to replace the word (contact-us) with the page name in your site

also this code need to be added to functions.php of your theme (or child theme) at the end of it

add_action( 'wp_print_scripts', 'my_deregister_javascript', 100 );
function my_deregister_javascript() {
if ( !is_page('contact-us') ) {
wp_deregister_script( 'contact-form-7' );
}
}
add_action( 'wp_print_styles', 'my_deregister_styles', 100 );
function my_deregister_styles() {
if ( !is_page('contact-us') ) {
wp_deregister_style( 'contact-form-7' );
wp_deregister_style( 'contact-form-7-rtl' );
}
}

hope i saved you 2 or 3 sec in load time 🙂

Good Luck

Advertisements