How to Remove Unused CSS and JavaScript in WordPress

When you are looking for a way to remove unused CSS and JavaScript code from your WordPress website, you are most likely diving deep into improving site performance. After all, any code that the browser doesn’t have to load is code that doesn’t slow it down.

However, it’s also generally a good idea to regularly check your WordPress site if you can remove any CSS or JavaScript that remains unused. This is especially true when changing your theme or installing new plugins. In this post, you will learn how to achieve this both manually and via plugin.

What is Unused CSS and JavaScript?

Unused code is exactly what it sounds like: CSS and JavaScript markup that loads when someone views your site but doesn’t actually do anything for its display.

As pointed out, this is bad because it can reduce your page loading speed. This in turn can affect your user experience, revenue, and even search rankings. So much so that when you speed test your website, you can sometimes find a warning like this in the results:

unused css javascript warning in speed test

Where Does This Come From?

The first question you might have is why there is unused code on your website to begin with. If you run a WordPress site, there are many components that can add code to your pages.

First of all, there is the theme, which is responsible for the design. It brings its own CSS style sheets and JavaScript files with it. Here, theme developers will most often put all CSS code into one file called style.css that covers the markup for all kinds of elements (buttons, tables, forms, galleries, widgets, etc.). Most of the time, these load regardless of whether the elements in question are even present on the page.

potentially unused css in wordpress style sheet example

So, out of the gate, there is most likely at least some CSS on your pages that you are not using. In addition, many themes come with their own scripts for special functionality. Their delivery might not always be optimized.

Then, if you install plugins, they can include their own resources. For example, if you add a contact form to your site, the plugin you use for that will likely call some CSS upon load for styling. Same for page builder plugins, which come with a whole bunch of design options.

In addition, there might be all sorts of other scripts loading together with your pages like web fonts or analytics software. Though many of these are small and usually load quickly, they can easily add up.

Plus, some resources load in places where they are not needed. For example, a contact form plugin might load files even on pages where there is no contact form.

If it starts to hamper your performance, it’s time to learn how you can remove these unused CSS and JavaScript assets so that WordPress doesn’t load them unnecessarily.

How to Find Unused Code on Your WordPress Site

So, how do you identify whether there is any code on your pages that shouldn’t be there? There are several ways to go about this.

1. Speed Testing Tools

One way is to use the above mentioned speed testing plugins. When you run your page through Google PageSpeed Insights, you might see the warning shown above under Opportunities. When you click on it, the service will even display the file that’s causing the warning.

pagespeed insights shows which wordpress files contain unused css and javascript

GTmetrix will also list this as an issue under Structure including the files that are causing it.

unused css warning in gtmetrix

2. Browser Developer Tools

Another option is to use browser developer tools. In Chrome, open the tools (via the menu, then More Tools > Developer Tools or Cmd/Ctrl+Shift+I), hit Esc to open the drawer, then use the three-dot icon in the upper left corner to open Coverage.

open coverage in chrome developer tools via menu

Alternatively, can also get there by hitting Cmd/Ctrl+Shift+P to open the command line. Type in “coverage” and select Show Coverage from the list that shows up.

open coverage via chrome developer tools command line

Once ready, click the reload button to start capturing. This will give you a list of files that the browser loads for the page and information like their type, size, and, most importantly, the percentage and bytes that the page is not using.

coverage data of unused css javascript in chrome developer tools

Double click any of the files to see a line-by-line breakdown of which code is actually contributing to the page and which isn’t.

show unused css in file in chrome developer tools

This can be quite sobering but is a great place to start to figure out what code on your site is actually necessary and which remains unused.

Leaves the question, do you have to test every single page like that?

If your site is small, this might be possible. However, if not, start with your most important pages like the homepage, your cornerstone articles, about page, shop, etc. Alternatively, target your slowest pages first, where it’s most likely that you will find this kind of issue. Check the website speed testing article for more details.

Removing Unused CSS and JavaScript With a WordPress Plugin

Alright, now that we know how to find unused code on your site, it’s time to talk about how you can get rid of it. The first thing we want to look at is how to do so with a WordPress plugin.

There are a few options that make this relatively easy. For this example, we will use the Asset Cleanup plugin. You will find some more options below.

1. Install the Plugin

The first thing you need to do is install the plugin. For that, go to Plugins > Add New and search for it by name. Locate Asset Cleanup in the search results and click the Install Now button, then click Activate once it’s done installing.

install asset cleanup plugin

2. Enable Test Mode

Before starting to remove unused CSS and Javascript code, you need to switch your WordPress site to test mode. That way, you are able to try out stuff without immediately affecting your website and potentially breaking things. All changes that you make are only visible for you as the administrator. Alternatively, use a development or staging site.

You find the option for test mode under Settings > Test Mode.

enable test mode in asset cleanup

Here, click the slider next to Enable Test Mode? and then Update All Settings at the bottom. When you have done everything right, there should be a green indicator next to Test Mode in the sidebar and it should say TEST MODE is ON in the WordPress admin bar.

asset cleanup test mode enabled

3. Start Unloading CSS and JavaScript

After that, you want to go to CSS/JS Manager.

asset cleanup css js manager

Here, on the first page, you see a list of CSS and JavaScript files that load on your homepage. To prevent them from doing so, simply use the slider where it says Unload on this page. Alternatively, use the checkbox Unload site-wide to disable a particular file for your entire website.

unload files in asset cleanup

Click Update at the bottom to save your changes.

At the top, you can use the tabs to do the same for posts, pages, custom post types, and media pages. Just search for a content piece by title or id and you get the same options as for the homepage.

remove unused css javascript from wordpress pages with asset cleanup

In addition, the Asset Cleanup plugin also adds the same functionality to the bottom of the WordPress editor where you can make changes while writing.

asset cleanup options in wordpress editor

4. Test and Commit

Before accepting your changes, it’s time to test if everything works well. In test mode you can only do this manually by loading and looking at pages. As mentioned, changes only apply to you, therefore, you can’t pick them up with speed testing tools. For that exact reason, doing this on a development site might be the better idea.

Once satisfied, go back to the settings and disable test mode. Again, Update All Settings to save. When you now re-run the test in your speed testing tool, the changes should be visible.

no more unused css javascript warning in speed test

Other Options

Besides the plugin above, there are a few other solutions that can help you remove unused CSS and JavaScript assets from your WordPress website:

  • CSS JS Manager — Another plugin that allows you to remove individual CSS and JavaScript files from your WordPress pages if you deem them unused. It’s a little more complicated to handle but still powerful.
  • WP Rocket — This paid caching plugin has an option to get rid of both unused CSS and delay execution of JavaScript on your site. Both are methods to get rid of the warning from Google, more on that below.
  • Perfmatters — Another paid plugin to increase page speed in different ways. It comes with a script manager that allows you to determine what pages your JavaScript files should and should not load on.

How to Manually Remove Unused CSS and JS in WordPress

Alright, now that we know the plugin route, it’s time to look at how we can do the same thing by hand. We will go over two methods that are probably the most practical

The first thing you want to do for that is to create a child theme so any changes you make won’t be overwritten when you update your main theme.

1. Split the Style Sheet

One of the main problems when trying to remove unused CSS from your WordPress site that in the majority of cases almost all of it is in one single style.css file. In the Chrome coverage example above, we have seen that only a small percentage of that file is actually in use on a given page. For that reason, it can make sense to split the main style sheet into several smaller ones that only load where they are needed.

This might look like this:

  • base.css
  • forms.css
  • front-page.css
  • table.css
  • comments.css

You can use a tool like UnCSS to generate only the CSS your page is actually using. Input the HTML and CSS of the page you want to optimize and it will spit out the shortened markup.

uncss website

You can copy that into a new style sheet and upload it to your child theme. After that, it’s all about dequeueing any existing CSS files and inline code and enqueuing your new, optimized style sheets.

You can even do this conditionally and use different files for different pages. However, this is a bit outside of the scope of what we can cover here, however, you can find a good example including code snippets over on WebPerfTools.

2. Delay JavaScript Files or Load Them Conditionally

In order to get rid of the warning for unused JavaScript you have two options: either delay your scripts being loaded or disable them from pages where they are not needed.

The most common way to delay JavaScript is to move the scripts to the footer. This is easiest if you are directly editing the (child) theme that enqueues the script in question. In that case, you just need to set its last parameter to true and it will automatically load in the footer. Here’s what that looks like:

function ns_load_scripts_in_footer() {
        wp_enqueue_script('script-name', get_template_directory_uri() . '/scripts/myscript.js', '', '', true );
}

add_action( 'wp_enqueue_scripts', 'ns_load_scripts_in_footer' );

Similarly, you can also register it for certain conditions, such as when the browser loads a page where you want it to appear. Here’s how to load the same script only on your homepage:

function ns_load_scripts_in_footer() {
        if (is_home()) {
                wp_enqueue_script('script-name', get_template_directory_uri() . '/scripts/myscript.js', '', '', true );
        }
}

add_action( 'wp_enqueue_scripts', 'ns_load_scripts_in_footer' );

Finally, if your problem is with a script that is not in a separate file but output directly on the page, you need to find where it comes from and then copy it to its own file and upload that to your child theme. From there, you can then register it to load in the footer as shown above.

Conclusion

Removing unused CSS and JavaScript from your WordPress website is a great way to speed it up. It decreases page size, reduces HTTP requests, and makes your website leaner. As a consequence, it will be more pleasant to use for your visitors and look better to search engines — what’s not to love?

Above, you have learned where unused code comes from, how to locate it, and ways to get rid of it. You are now well equipped to implement these changes.

How do you deal with unused CSS and JavaScript files on your site? Any additional tips or tools to share? Let us know in the comments!

The post How to Remove Unused CSS and JavaScript in WordPress appeared first on Torque.


Share on Google Plus

About admin

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.

0 comments :

Post a Comment