MENU

How to stop JavaScript and CSS outside of Contact Form 7 pages

form

If you use Contact Form 7, the JavaScript and CSS used by Contact Form 7 will be loaded on all pages.

Using JavaScript or CSS related to pages that do not use Contact Form 7 will slow down the speed, so I would like to avoid it.

Limit the loading of related JavaScript and CSS to pages that are actually using Contact Form 7.

Since the specifications of Contact Form 7 were changed after updating to 5.4, the description method up to that point became invalid.
The description method of both the latest 5.4 or later and the old version 5.3.2 or earlier is listed.

In the code example below, the page using Contact Form 7 is a fixed page and the slug is “inquiry”.

Add it to functions.php of your theme according to your environment.

* Slug is the URL of the page that can be changed by perming *

5.4 ~

add_action( 'wp_enqueue_scripts', function() {
	if( !is_page('inquiry') ){
	  wp_dequeue_style( 'contact-form-7' );
	}
});
add_action( 'wp_footer', function() {
	if( !is_page('inquiry') ){
	  wp_deregister_script( 'contact-form-7' );
	  wp_deregister_script( 'google-recaptcha' );
	}
});

Before 5.3.2

add_action( 'wp_enqueue_scripts', function() {
	if( !is_page('inquiry') ){
	  wp_dequeue_style( 'contact-form-7' );
	  wp_deregister_script( 'contact-form-7' );
	  wp_deregister_script( 'google-recaptcha' );
	}
});

The above code will also stop Google’s reCAPTCHA used by Contact Form 7.

If you are using it on multiple pages, the code will be as follows.

5.4 ~

add_action( 'wp_enqueue_scripts', function() {
	if( !is_page( array( 'inquiry','inquiry2','inquiry3','inquiry4' ) ) ){
	  wp_dequeue_style( 'contact-form-7' );
	}
});
add_action( 'wp_footer', function() {
	if( !is_page( array( 'inquiry','inquiry2','inquiry3','inquiry4' ) ) ){
	  wp_deregister_script( 'contact-form-7' );
	  wp_deregister_script( 'google-recaptcha' );
	}
});

Before 5.3.2

add_action( 'wp_enqueue_scripts', function() {
	if( !is_page( array( 'inquiry','inquiry2','inquiry3','inquiry4' ) ) ){
	  wp_dequeue_style( 'contact-form-7' );
	  wp_deregister_script( 'contact-form-7' );
	  wp_deregister_script( 'google-recaptcha' );
	}
});

Please change the parts of’inquiry’,’ inquiry2′,’ inquiry3′, ‘inquiry4’ according to your environment.

Let's share this post !
  • Copied the URL !
  • Copied the URL !

Author of this article

Comments

To comment

TOC