Blog / WordPress / How to Remove Unused CSS JS Files in WordPress

How to Remove Unused CSS JS Files in WordPress

remove unused css js files in WordPress
Cristian Antohe
Last Updated: 09/07/24

WordPress sites typically use a lot of plugins. These can include contact form tools, page builders, ecommerce solutions like WooCommerce, and more. So, when you try to optimize page loading times, all this added software can cause you to hit a roadblock.

You might have already tried the more straightforward optimization strategies like switching to a faster web host, enabling caching, compressing images, and removing unnecessary plugins and themes. In that case, your next best step may be to optimize or remove unused CSS and JavaScript files in WordPress.

In this post, we’ll explain how plugins load CSS and JavaScript. After that, we’ll show you how to remove unused CSS and JavaScript files in WordPress. Let’s get to it!

Why You Should Remove Unused CSS and JavaScript

When you install plugins and themes, you can end up with extra code that isn’t needed to display your web page. But, the problem is that this code still gets loaded on your website.

Therefore, it can take a bit longer for the browser to render your page, which can disrupt the user experience (UX). Not only that, but slower loading times negatively impact your search engine rankings.

If you’re not sure whether this is an issue for your site, you can carry out a quick Google PageSpeed Insights test. In the Diagnostics section, you might see a recommendation to Remove unused CSS or Remove unused JavaScript:

Check if you have unused CSS and JavaScript

If you click on the option, you’ll find a list of the specific CSS and JavaScript files that are causing the issue.

To give you an idea, we redesigned our site a few years back, and made it a personal quest to limit the number of CSS and JavaScript files here at Cozmoslabs. After going through the scripts that load on our homepage, we managed to go from 15 JS scripts to just 4. Plus, we reduced CSS files from 11 to 2.

Why Do Plugins Load So Many CSS and JavaScript Files?

It makes a lot of sense to invest a bit of time to remove unused CSS and JS files in WordPress. If you take any plugin that offers a shortcode or widget for the user, chances are it will load its CSS and JavaScript files site-wide by enqueuing scripts and styles.

This loads the style.css and filename.js files site-wide, regardless of the fact that you’re using a particular shortcode on a single page (or a widget on a certain custom post type). Essentially, there’s no way to choose where that particular CSS/JS file gets loaded.

How to Remove Unused CSS JS Files in WordPress (In 3 Steps)

Now, let’s talk about how you can remove unused CSS and JS files in WordPress.

Beginners may be more comfortable removing CSS and JavaScript files using a plugin like Asset Clean Up. There are also tools for minifiying JS and CSS code like the WP Rocket cache plugin or PurgeCSS.

However, these solutions don’t have the flexibility to target entire custom post types. Plus, you might not want to install yet another plugin. That said, they are a lot easier to use for non-technical users than writing your own conditional rules.

Other solutions to this problem include combining assets. But even then, large CSS and JS files will slow down the load time of your WordPress site. This is especially the case for mobile devices because it has to render all those CSS files and execute all that JS code.

You also have the option to install a Content Delivery Network (CDN) to improve your page speed and boost your search rankings. But, this will still load unneeded resources.

Therefore, we’re going to show you how to remove unused files manually in WordPress in three steps. Before you attempt this, make sure to create a fresh backup of your website. This way, you can restore it in case you accidentally make an error.

Step 1: See Which Scripts are Getting Loaded on Your Site

In order to remove unused scripts, you should first find out which exact files get loaded by your WordPress themes and plugins. To do this, you can look at the source code, make a list of files, and then search exactly where they get loaded within each plugin:

Remove unused css js files in WordPress

While this approach does the job, there are other solutions out there. For example, in the first section, we showed you how to do this using Google PageSpeed Insights. Additionally, you can use browser developer tools or browser extensions like Sniper CSS.

Step 2: List All Loaded Scripts with wp_enqueue_script

First things first, we’ll create a simple custom plugin that will host all of your code. To do so, you’ll need to set up a new file called wp_remove_assets.php and add the code inside this gist.

Before we can remove unused CSS and JS files in WordPress, we’ll first look at what gets loaded. WordPress uses two global variables to store scripts and styles:

  • $wp_scripts
  • $wp_styles

If you do a var_dump of both global files on the front-end, you’ll be able to see all the registered scripts (by plugins, themes, and WordPress itself) as well as the ones currently loaded on your page.

We’re mainly interested in the ones that get loaded. We’re looking into the wp_print_footer_scripts hook with a very high priority to make sure all scripts finish loading before listing them.

Also, this listing gets displayed only if you’re a logged-in administrator. So your users or search engines will never see the listing.

The wra_print_assets and wra_asset_template will be listing:

  • the current number of the CSS/JS file
  • $handle– the handle is the unique name used by wp_enqueue_scripts to load a script just once
  • $src– the source is the location of the file
  • $deps– this stands for dependencies. For example, some files require other libraries like jquery
  • $ver– the version of the script isn’t required if it’s the current version of the CSS/JS file

Going forward, we’ll only need the handle of the CSS/JS files, but it is nice to see this information listed to get an idea as to why some files are loaded.

Step 3: Remove Unused CSS and JavaScript Files in WordPress

There are four main functions when you want to remove unused CSS and JavaScript files on the WordPress front-end:

You can use WordPress conditional tags to target a particular page or an entire custom post type.

The really cool part of doing it like this is that you can use WordPress conditional tags to target a particular page or an entire custom post type. This gives us the flexibility we need to load our CSS/JS files exactly where they are needed.

Remove Scripts That Won’t Work with the wp_dequeue_script

Sometimes scripts are added differently. The most common way is to simply output the script or style tag directly in the header or footer.

Now, this is wrong for many reasons:

  • It’s not possible for other developers to dequeue assets.
  • Not being part of $wp_scripts global variable means that conflicts can occur, since another plugin can load a local version of jQuery.
  • It’s not the best practice and should not be used unless you really know what you’re doing.

To remove a script like the one above, you can remove the entire hook from executing. We’re going to use the <a href="https://codex.wordpress.org/Function_Reference/remove_action" target="_blank" rel="noopener">remove_action()</a> function that WordPress provides.

When removing actions, it’s best to remember:

  • The priority of the add_filter() declaration counts when doing remove_filter()
  • The remove_filter() function should be called on a hook after the add_filter() we want to be removed was added

In our particular case, when removing unused CSS/JavaScript files, one of the scripts was jetpack.css that was added in a particular way that wp_dequeue_style() didn’t work.

For some reason I couldn’t dequeue the jetpack.css file. However, there was a hook inside the Jetpack implode_frontend_css() function that allowed us to stop loading that particular file. See the function wra_remove_jetpack() inside the plugin code.

A Better Way for Plugins to Include CSS/JS Files

Plugins load CSS and JavaScript files globally for a variety of reasons. The main reason is that as a developer, there’s no standard way to find out if your shortcode is used on a page or not.

Therefore, most developers load all assets globally. Plus, it’s recommended by WordPress.org. But, with so many examples of loading scripts globally, it’s easy to see why most WordPress sites load too many resources while only needing a few.

Factors to Consider Before Loading Assets This Way

We’ve been using this technique on almost all our plugin assets for quite some time. Basically, we have a global variable that gets initiated in our shortcode, and if it’s set and true, we’re loading our assets like so.

Unfortunately, there are drawbacks to this as well. For example, the scripts need to be added to wp_footer with a late priority. If you add them to wp_enqueue_scripts, the global variable has a good chance of not being set.

Additionally, if you need something added in the header of the site, this won’t work. And finally, in wp_enqueue_script(), you have to set $in_footer to true.

Conclusion

WordPress sites are made up of PHP, HTML, JavaScript, and CSS code. However, many developers add assets globally in themes and plugins, which means they get loaded even if they aren’t needed.

Although there are plugins and tools that provide automatic solutions, you can also reduce unused CSS and JavaScript manually. This way, you can speed up your website, and improve your search rankings, without relying on additional plugins to do the job.

Are you running a ton of plugins to get all the necessary functionality for your WordPress membership site or online community? When you use an all-in-one plugin solution, you can reduce excess CSS and JSS on your site.

In that case, consider using the Paid Member Subscriptions plugin:

Accept (recurring) payments, create subscription plans and restrict content on your website. Easily setup a WordPress membership site using Paid Member Subscriptions.

Get Paid Member Subscriptions

Do you have other suggestions on how plugins can load CSS and JavaScript files in a more mindful way? Let us know in the comment section below!

From the blog

Related Articles

roundup wordpress ecosystem january2

Roundup of WordPress ecosystem #1 – January 2017

Author: Patricia Borlovan
Last Updated: February 9th, 2017

After writing the article "Overview of the WordPress Community in 2016" and getting feedback for the article on various platforms, I decided to continue writing them, but I changed its name into "Roundup of WordPress ecosystem". This is the first article from a monthly series that will showcase what happened around the whole ecosystem in […]

Continue Reading
feb_mar_roundup_wp_ecosystem

Roundup of WordPress ecosystem #2 – February & March 2017

Author: Patricia Borlovan
Last Updated: April 11th, 2017

There were two interesting months within the WordPress ecosystem with events that are here to impact the course and development of the platform. We saw WordPress getting important security updates and a brand new design for the plugin repository and also witnessed to a significant acquisition. With this being said, let's dive into the summary […]

Continue Reading

How to Password Protect Content, Posts, and Categories in WordPress

Author: Rishi Lodha
Last Updated: July 9th, 2024

There are many use cases for password-protected content in WordPress. For example, you might be a content creator who wants to monetize premium content in the form of subscriptions or memberships. As with everything related to WordPress, password-protecting posts doesn’t have to be difficult. If you’re wondering how to password-protect WordPress content, posts, and even […]

Continue Reading

32 thoughts on “How to Remove Unused CSS JS Files in WordPress

    Hey Cristian,

    Regarding your issue with the Jetpack actions you’re unable to remove… These are added as methods of a class instance, so to remove them, you need to get a reference to the class instance first.

    Fortunately, Jetpack provides a way to retrieve that instance through the badly named `Jetpack::init()` method: https://github.com/Automattic/jetpack/blob/257d473f022f2b75fe45719c22d2f655e3eafdee/class.jetpack.php#L308-L319

    So, to remove these actions, something like the following should work:

    https://gist.github.com/anonymous/8d6face1e4161172cd6d655ce739ba04#file-gistfile1-txt

    Reply

    Thanks for this tutorial. Exactly what I was looking for to get my site faster.

    Reply

    There’s actually no need to create a global variable (and you shouldn’t) if you want to only load scripts/styles on pages where the shortcode is used. One method is to use wp_register_script() to register the script in the wp_enqueue_scripts hook, and then to use wp_enqueue_script(‘script-hook’) in the plugin callback. The script will then only be loaded if the plugin callback is called.

    Reply

    What is needed is a campaign to get every plugin owner to improve their plugins so that scripts and css files are only loaded if they are going to be used.

    Reply

    With http2 combining multiple static files into one is no longer necessary and a bad idea. However, your point about the processing overhead of unused CSS and JS files is valid.

    Reply

    I’m gone to convey my little brother, that he should also go
    to see this web site oon regular basis to take updated from hottest information.

    Reply

    I Used Genesis Child Theme.
    I have Many Problems Of Java Script & inline CSS.
    How To Solve It Please

    Reply

    I am curious, where will the debug message gets output? Is it to the browser console?

    Reply

    No. Directly after your footer if you’re logged in as an administrator.

    Reply

    I have installed a plugin unused assets cleaner but it not work properly… is there any plugin to remove unused css and js codes…?

    Reply

    Fantastic plugin concept, this is going in my WP performance tool belt. I could only find partial snippets on Stackoverflow which addressed this unused asset issue. So thanks Cristian!

    I think I found a script that can’t be removed using the methods outlined in this article, and I would be curious to hear your feedback.

    I’ve been trying to deregister/dequeue an asset from the Visual Composer page builder plugin, as it is causing some render-blocking and is also performing a non-performant animation right at page load.

    The asset is registered in this function:

    protected function shortcodeScripts() {
    wp_register_script( ‘vc_jquery_skrollr_js’, vc_asset_url( ‘lib/bower/skrollr/dist/skrollr.min.js’ ), array( ‘jquery’ ), WPB_VC_VERSION, true );
    }

    But it is never enqueued as far as I can tell. When I deregister and dequeue it, it is removed from the list of assets displayed below the footer, but when I view source the file is still being loaded and it is still running on page load.

    Ideas?

    Reply

    I can not remove unused CSS from my site https://www.fileour.com/ without much effort. Please do I have such a plugin? Automatically remove the unused css from my site. Remember I’m using the Autoptimize WordPress plugin. I’ll be very grateful to you.

    Reply

    Thanks for this tutorial. Good post with exactly what I was looking for to get my site faster. Concerns its a bit technical

    Reply

    Wow.. This just helped me to speed up my wordpress site.

    Reply

    But what i need to do with the “wp_remove_assets.php” file? where to put it??

    Reply

    Thanks this helped me to work my site better.

    Reply

    I have lot’s of unused css and javascript in my site. I don’t want to add another plugin to my website, I just want to remove it manually. Thanks for this tutorial!

    Reply

    Please can you explain through a video.

    Reply

    i facing loading spped issue in my blog bt after follow this post my blog loading speed is fast thankyou so much sharing this awesome infomation very useful.

    Reply

    Thank You lot’s of Support I really Like You

    Reply

    My website speed facing many speed issue, with your help my speed issue solved, thank you so much you make my day.

    Reply

    Add this to your plugin inside “function wra_list_assets()” before first ECHO to see if your page uses Elementor.

    [code]
    global $post;
    if( \Elementor\Plugin::$instance->db->is_built_with_elementor($post->ID)) echo ‘ Elementor’;
    [/code]

    But I’m not really clear then how to block or allow Elementor js and CSS. Can you relate it to JetPack or BB so I can see an example?

    Reply

    CSS is making the website a little bit slower, but there are lots of cssand javasript minifying plugins available in WordPress, however you can checkout hindi content related to tech @ helpmebro.in

    Reply

    Hello Cristian Antohe Sir,

    i facing loading spped issue in my website but after follow this post my blog loading speed is fast thank you very much sharing this valuable infomation
    Check My blog speed

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.