Use JS/CSS only where necessary

One of the methods of speeding up the speed of downloading WordPress sites – it is use additional external JS/CSS files only where necessary.
I wrote about this 2 years ago, but judging by the sites that I was asked to optimize, the problem is still actuallity.
Today I want to tell you why load external JS and CSS files on all pages – it is bad, and also give a simple example.

In practice, very often plugins are used for certain specific pages, posts or categories.
For example, the contact form (feedback) needed on the contact page only, for other pages it is not needed. Or sliders and carousels – they are used only on the main page of the site or for a rubrics. Or galleries – they are used only for certain types of posts.

If you use the popular plugin Contact Form 7, I suggest you do a little experiment and you’ll see everything yourself.
1 – Open any page of your site, except the page with the contact form (feedback).
2 – Switch to html mode (Ctrl + U in Firefox or Google Chrome).
3 – Enable search mode (Ctrl + F) and enter “contact-form-7” in the search field.
Have you found the result? The file is not used, but it is connected. And if you have 10 unused files? Or 20?

Most plugins enqueue external JS and CSS files using the wp_enqueue_script function:

Everything is fine, everything works, does it really need something else?
Yes need. The plugin author does not know on which page his plugin will be used, so he does so that the plugin works everywhere, on all pages.
But we know. Therefore, we can use additional check and enqueue files only where necessary.

Let’s do it on the example of Contact Form 7. I do not like hardcode, so I will not modify the plugin myself and will add a check in the functions.php of the current theme.

Instead of “contact”, specify permalink or ID of your page with contacts. For CSS, use wp_deregister_style and wp_print_styles, respectively.
As you can see, everything is quite simple, but if you have any questions – welcome to comments.