Only Load Contact Form 7 When It Is Needed
Why Don't Plugin Developers Do This by Default?
You may be wondering why plugin developers don't build this functionality into their plugins by default. The reason is finding out where their plugin is actually being used is difficult. Everyone has a different implementation of the same plugin and it would be impossible to account for every use. You could only load Contact Form 7 assets in the shortcode, but some themes might have it loaded by a php function, or they might be loading it by Ajax. Therefore detecting all of these use case is difficult. That being said, if you only use Contact Form 7 on your contact page, it is fairly easy to only load those resources on that page. One way of doing this is by checking for the shortcode.function contactform_dequeue_scripts() {
$load_scripts = false;
if( is_singular() ) {
$post = get_post();
if( has_shortcode($post->post_content, 'contact-form-7') ) {
$load_scripts = true;
}
}
if( ! $load_scripts ) {
wp_dequeue_script( 'contact-form-7' );
wp_dequeue_style( 'contact-form-7' );
}
}
add_action( 'wp_enqueue_scripts', 'contactform_dequeue_scripts', 99 );
You can add this code to the following places:
- functions.php file
- child theme
- site-specific plugin.
// Deregister Contact Form 7 JavaScript & Css files on all pages without a formfunction contactform2_deregister_javascript_css() { if ( ! is_page( 'contact-us' ) ) { wp_deregister_script( 'contact-form-7' ); wp_deregister_style( 'contact-form-7' ); }}add_action( 'wp_enqueue_scripts', 'contactform2_deregister_javascript_css', 100 );- functions.php file
- child theme
- site-specific plugin
Scott Hartley
Founder & CEO, Sert Media
Founder and CEO of Sert Media, a Nashville-based digital marketing agency. Scott has spent over 15 years helping businesses grow through SEO, web performance optimization, and strategic digital marketing. His deep expertise in WordPress development, site speed, and technical SEO has guided hundreds of brands toward measurable results. When he's not auditing Core Web Vitals or refining campaign strategies, he's writing about the tools, techniques, and trends shaping the modern web.
Related Articles
How to Add Security Headers to WordPress Using Cloudflare Transform Rules
If you've ever run your WordPress site through securityheaders.com and gotten a D or F…
Use This Cloudflare Rule To Reduce Plugin Hack Attempts
Cloudflare Firewall Rules give you a lot of flexibility in further protecting your website. Here…
Set Up Cloudflare's Automatic Platform Optimization Feature
Automatic Platform Optimization (APO) is a new feature from Cloudflare that allows you to cache…