Loading JavaScript and stylesheet only when it is necessary

In its default settings, Contact Form 7 loads its JavaScript and CSS stylesheet on every page. You might think it would be redundant or wasteful, and want to load them only on those pages that contain contact forms. I understand the feeling, but there is a technical difficulty for a plugin in knowing whether the page contains contact forms or not at the start of loading. However, I can show you a way to work around that.

Step 1: Stop loading the JavaScript and CSS stylesheet on all pages

When the value of WPCF7_LOAD_JS is set to false (default: true), Contact Form 7 does not load the JavaScript. You can set the value of this constant in your wp-config.php like this:

define( 'WPCF7_LOAD_JS', false );

Likewise, you can control the loading of the CSS stylesheet with WPCF7_LOAD_CSS. Contact Form 7 does not load the CSS stylesheet when the value of WPCF7_LOAD_CSS is false (default: true). You can set it in the wp-config.php like this:

define( 'WPCF7_LOAD_CSS', false );

Or, you can also disable the loading of the JavaScript and CSS by adding a few lines of code into your theme’s functions.php file, like this:

add_filter( 'wpcf7_load_js', '__return_false' );
add_filter( 'wpcf7_load_css', '__return_false' );

Now you have succeeded in stopping the loading of the JavaScript and CSS stylesheet, but, unfortunately, you’ve also killed them on pages that contain contact forms — so we really need to get them back on the right pages. So, the next step is what you’ll need to load the files on to the explicit pages in which you need them.

Step 2: Load the files on pages which contain contact forms

For example, let’s say you have a page named “Contact” and it is the only page that contains a contact form. And suppose that you have a template file for the “Contact” page named ‘contact.php’ in your theme folder. Now you will need to load Contact Form 7’s JavaScript and CSS stylesheet specifically on the “Contact” page.

To do this, you must edit the ‘contact.php’ template file and insert the following lines into it:

<?php

if ( function_exists( 'wpcf7_enqueue_scripts' ) ) {
  wpcf7_enqueue_scripts();
}

if ( function_exists( 'wpcf7_enqueue_styles' ) ) {
  wpcf7_enqueue_styles();
}

?>

Note that wpcf7_enqueue_scripts() and wpcf7_enqueue_styles() must be called before wp_head() is called.

Just another contact form plugin for WordPress. Simple but flexible.