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.

默认的,Contact Form 7 在每个页面载入他的 javascript 和 CSS。你或许认为这是多余的,浪费,你想在有表单的页面才载入。我能理解这种感受,但是在插件里很难找到页面里是否有表单在载入的时候。但是,我可以告诉你一个办法解决。

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

第一步:在所有页面停止载入 javascript 和 CSS。

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:

当 WPCF7_LOAD_JS 的值设置为 false (默认:true),Contact Form 7 就不会加载 Javascript, 你可以在 wp-config.php 里设置这个静态变量:

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:

同样的,你可以用 WPCF7_LOAD_CSS 控制 CSS 的载入。当 WPCF7_LOAD_CSS 设置为 false (默认: true) 时,Contact Form 7就不会载入 CSS 样式表。你可以在 wp-config.php 里设置这个静态变量:

define('WPCF7_LOAD_CSS', 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:

	if ( function_exists( 'wpcf7_enqueue_scripts' ) ) {

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