WordPress: Which Plugin Loads Script? (Contact Form 7, jQuery)

Recently I was benchmarking a site and wondering why jQuery (no offense) was loaded on every page when I was very sure I did not include it in the custom written theme for that site.

As it turns out Contact Form 7 requires jQuery. On every load.

When you know that you only provide a contact form on one page of your entire website, it might be overkill to load jQuery on every page, even though it's not a requirement for any of the other JavaScript code on your website.

Conditionally Loading JavaScript Code with WordPress

If you want to decide when what gets loaded as JavaScript files into your WordPress theme, you can even wp_dequeue_style and wp_dequeue_script when writing your theme specific code.

My solution for not loading the jQuery code for Contact Form 7 on every page was the following:

functions.php
add_action('wp_enqueue_scripts', 'unload_wpcf7');

public function unload_wpcf7(){
  if(!is_page()) {
    wp_dequeue_script('contact-form-7')
    wp_dequeue_style('contact-form-7');
  }
}

I used the conditional function is_page() to shave off jQuery for the initial page load for both blog posts and the front page, since jQuery really is of no use to those pages.

The official documentation has a page on loading styles and scripts only when necessary, but they all break existing plugin code or are outside the scope of a themes capabilities to override, so I found the above code much more useful.

What Plugin uses wp_enqueue_script/style

To figure out which WordPress Plugin or which function in a theme is using the wp_enqueue_script of wp_enqueue_style function you can make use of the following stackoverflow post: Know which plugin is calling JS in wp_head()?

It sure helped me when debugging my way to the source of the unwanted inclusion.

Summary

Loading scripts and styles conditionally should be something that every web developer keeps in mind, it's kind of a cheap version of code splitting, built right into WordPress.

If you're wondering

Why on earth is jQuery loading in WordPress on this page?!
You might just be able to dequeue your frontend code for most pages/posts.

Tagged with: #Contact Form 7 #jQuery #WordPress

Thank you for reading! If you have any comments, additions or questions, please tweet or toot them at me!