Only include Contact Form 7 javascript and CSS when needed

The Contact Form 7 is a great WordPress plugin for adding contact forms to your site. The plugin is very easy to use and make nice contact forms with.

The bad news is that the plugin includes javascript and CSS on every page which makes your site load slower than necessary. The good news is that there is an easy fix for it.

By adding the two following code snippets to your themes functions.php you can remove the javascript and CSS from all pages that don’t use it which makes your site load faster.

Remove Contact Form 7 javascript

add_action( 'wp_print_scripts', 'deregister_cf7_javascript', 100 );
function deregister_cf7_javascript() {
	if ( !is_page(100) ) {
		wp_deregister_script( 'contact-form-7' );
	}
}

Remove Contact Form 7 CSS

add_action( 'wp_print_styles', 'deregister_cf7_styles', 100 );
function deregister_cf7_styles() {
	if ( !is_page(100) ) {
		wp_deregister_style( 'contact-form-7' );
	}
}

In both code snippets, change the number 100 to the id of the page where you have added the contact form or use the page slug instead.

About Fredrik Malmgren

Fredrik Malmgren is an entrepreneur, project manager and developer specialized in WordPress. Read more about me or get in contact with me. You can also find me on Twitter. (@fredrikmalmgren).
This entry was posted in Plugins, Tutorials, WordPress and tagged , , , , , , . Bookmark the permalink.

29 Responses to Only include Contact Form 7 javascript and CSS when needed

  1. Works like a charm!
    Thank you for sharing it! It reduced the loadtime and now I’ll use in my other WordPress-sites.

  2. Nabil says:

    Would you recommend one to use a caching plugin such as W3 Total Cache (and not get the CSS/javascript to load) or to use your fix?

    I’m voting for the first option since it makes your site load even more faster :)

    /Nabil.

    • Fredrik Malmgren says:

      I don’t know how cache works technically but why load something from the cache when not needed? I guess that it also takes time and resources although much less.

      So, maybe the best solution is to use them in combination.

      I saw that you are using both W3 Total Cache and Contact form 7. It would be interesting to see what happens if you add this fix to your site and compare the load time.

      Anybody have a better answer on Nabil’s question?

      • W3 Total Cache is merging and minifying all the css files or js files to one(if you’ve set it up to do so). So it is not a good thing using both methods, because then you will load the cf7 styles and scripts directly from the cf7 plugin AND from the cached files.

        I would compare the methods to each other. And see what fits your site best. Sometimes (not often!) W3 Total Cache is having the opposite effect, it makes your site slower. So you should always test your configuration with, for example, YSlow.

        We use W3 Total Cache for