Contact Form 7 is a great contact form plugin for WordPress, but it loads its Javascript and CSS on every page on your site, even when you don’t have a contact form there. Let’s fix that by loading the scripts and styles only on the pages that need them.
Add the following code to your theme or plugin to load the scripts and styles only on pages that have a contact form.
<?php
/**
* Contact Form 7
*
* Prevent the javascript and styles from loading on every page
* Load them only on the Contact page
*/
/* Removes the Contact Form 7 scripts and styles from all pages */
remove_action( 'wp_enqueue_scripts', 'wpcf7_enqueue_scripts' ); // Prevents the scripts from loading on all pages
remove_action( 'wp_enqueue_scripts', 'wpcf7_enqueue_styles' ); // Prevents the styles from loading on all pages
/* Adds the Contact Form 7 scripts and styles to the appropriate pages */
add_action( 'wp_enqueue_scripts', 'new_cf7_loader' ); // Loads the scripts and styles on the appropriate page(s)
/* Load the Contact Form 7 scripts and styles on the appropriate pages */
function new_cf7_loader() {
if ( is_page( array( 'contact', 'another page' ) ) ) { // Add all pages here that contain the contact form
wp_enqueue_style( 'contact-form-7', wpcf7_plugin_url( 'styles.css' ), array(), WPCF7_VERSION, 'all' );
wp_enqueue_script( 'cf7.jquery.form.js', wpcf7_plugin_url( 'jquery.form.js' ), array(), WPCF7_VERSION, true );
wp_enqueue_script( 'cf7.scripts.js', wpcf7_plugin_url( 'scripts.js' ), array(), WPCF7_VERSION, true );
}
}
?>