Remove Unused CSS

Still seeing the Reduce unused CSS audit in PageSpeed?

It's possible the Used CSS hasn't been applied to your pages yet, please refer to this guide for more information.

And, when the Used CSS is already applied, the audit may be present, but it should have a lower impact on the results.

Note: it's important to reduce the usage of safelist items and exclusions. Please consider reducing the exclusions to prioritize performance.

The Remove Unused CSS feature removes all CSS and stylesheets that are not used while keeping only the used CSS for each page.

This feature can be enabled under the File Optimization tab, inside the Optimize CSS delivery feature, like this:

enabling remove unused css

Remove Unused CSS is the recommended method of optimizing your CSS. If you have trouble with this option, check the status page, and/or try Load CSS Asynchronously instead.

In this article

The Remove Unused CSS option can help with the PageSpeed's Reduce unused CSS recommendation:

Reduce Unused CSS recommendation

The PageSpeed report will scan all your website’s stylesheets, and if it finds any CSS file with more than 2kb of unused code it will display this recommendation. 

Having unused CSS code will:

  • Increase unnecessary data transfer.
  • Slow down the rendering of the page, as the browser will have to read all the CSS before applying it.

You can read more about this recommendation here: https://web.dev/unused-css-rules/.


Feature benefits

  • Reduce overall page size
  • Reduce the number of CSS stylesheets to be loaded (fewer HTTP requests)
  • Reduce the page load time
  • Improve Core Web Vitals
  • Eliminate render-blocking CSS

It accomplishes this by automatically removing all the unused CSS, and keeping only the used CSS for each page.


Basic requirements for the feature to work

  1. You must have a valid WP Rocket license.
  2. Your site must be publicly accessible for the tool to work, which means it won’t be applied to logged-in users when User Cache is enabled, and it won't work on sites blocked from the public by htaccess authentication, "maintenance mode" plugins, or similar. 

    Note: This feature is automatically disabled in environments where the WP_ENVIRONMENT_TYPE constant is set to local, because it needs to establish a connection with WP Rocket's tool to generate the Used CSS.

  3. WP Rocket will reach the non-cached version of the page to scan the CSS. It will reach the pages of your site with the   ?wpr_imagedimensions=1&nowprocket=1&no_optimize=1 query string appended. Access to this query string must be allowed. The non-cached page shouldn't take more than 45 seconds to load, or it will time out in WP Rocket's SaaS.

  4. Your server, firewall, and/or security plugin has to allow-list:
    • These two user agents:
      • Desktop: WP-Rocket/SaaS Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36
      • Mobile: WP-Rocket/SaaS Mozilla/5.0 (Linux; Android 13; Pixel 5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Mobile Safari/537.36
    • And/or, the IPs found in this list.

    When WP Rocket can't access your site, the following admin notice will be displayed:

    firewall block admin notice

    It seems a security plugin or the server's firewall prevents WP Rocket from accessing the SaaS features. IPs listed here in our documentation should be added to your allowlists:

    - In the security plugin, if you are using one
    - In the server's firewall. Your host can help you with this
  5. WP-CRON or a real server-side cron job must be able to run, the latter is strongly recommended for the Used CSS generation to run properly.
  6. If you are using Wordfence, activate Learning Mode as described here.
  7. Cloudflare's Bot Fight Mode should be disabled.

Feature overview

The external tool will process the information and will generate the Used CSS, which corresponds to the CSS that is actually used in your pages.

HEADS UP! The process of generating and applying the Used CSS is not immediate, it's asynchronous.

Your site's pages will need a visit to trigger the Used CSS generation and further application.

The generation and application of the Used CSS in your site goes as follows:

Used CSS generation and application

A visit to a non-cached page, either manual or from the Preload, will start the Used CSS generation and application process. 

The URL of each page is sent to our API which will visit the URL and will create the used CSS for that.

WP Rocket will check every 60 seconds with the API to find which of the URLs that were sent have used CSS created for them.

For the ones that used CSS has been created for, WP Rocket will:

  1. Store the Used CSS in the server's disk, at the /cache/used-css/1/ folder. If you use WordPress Multisite, the folder named /1/ will change to reflect the site number.

    The resulting CSS will be compressed with the GZIP compression algorithm. The Used CSS files stored on the disk will have the .css.gz extension
  2. Clear the cache of the URL and preload that if the "Preload" feature is active.
  3. Remove all stylesheets and inline CSS from the HTML, and add the Used CSS as an internal CSS element after the </title> tag.

    The <style> tags will be preserved in the source code for compatibility but their content will be removed except for the ones that are automatically preserved.

If the Used CSS generation fails, WP Rocket will retry generating the CSS up to 5 more times.

To avoid overloading the CPU, the waiting time between each retry will be gradually incremented.

If the generation fails after the 5th retry, WP Rocket will retry to generate the Used CSS in these cases:

  1. After 3 days passes.
  2. The used CSS for a specific URL is cleared using the "Clear Used CSS of this URL" admin bar menu item while visiting the URL in the back end.
  3. The whole used CSS is cleared using the "Clear Used CSS" admin bar menu item while visiting WP Rocket's settings page.
  4. The Automatic clearing of Used CSS takes place.

How to check if Remove Unused CSS is working

You should see the following markup in your page's source code:

<style id="wpr-usedcss">.css-class{example: 0;}</style>

The <style> element with an id  wpr-usedcss will contain the resulting Used CSS for the page. 

At this point, you can run a PageSpeed test to see the benefits of this feature.

Note: While the overall page size will decrease, the HTML response body size may increase. This is because Remove Unused CSS will add the used CSS as an inline element into the HTML document. In the end, Remove Unused CSS will decrease the overall page size.

You can also jump to the Technical notes section of this article to get detailed information about this asynchronous approach.

Progress and admin notices

After activating Remove Unused CSS you will see an admin notice with a countdown and the following text:

Countdown admin notice

WP Rocket: please wait 52 seconds. The Remove Unused CSS service is processing your pages.

Remove Unused CSS will start processing and generating the used CSS for all the pages on your site, in groups of up to 100 URLs per 60 seconds.

The following message will appear on WP Rocket's settings page:

Homepage processed admin notice

WP Rocket: Your homepage has been processed. WP Rocket will continue to generate Used CSS for up to 100 URLs per 60 second(s). We suggest enabling Preload for the fastest results. To learn more about the process check our documentation.

Please note, that while the Remove Unused CSS feature will be ready to work for your pages when this notice is shown, only a visit to the pages will trigger the generation and later application of Used CSS. This is why using Preload is highly suggested. See more of how Remove Unused CSS works with Preload in the following section of this article.

You will see the admin notices in the scenarios below:

  • Adding or removing values in the CSS Safelist box
  • Switching themes
  • Clearing the Used CSS
  • Changing the Enable CDN options 
  • Updating WP Rocket

Using Remove Unused CSS with Preload

Enabling the Preload feature is highly recommended to have a more practical application of Remove Unused CSS, as it will automate some steps during the process.

When the Preload is active, it will simulate a visit to your pages creating the cache files, and will trigger these actions:

  • Trigger the Used CSS generation.
  • Apply the resulting Used CSS to the page.

Above's actions happen when you first enable Remove Unused CSS and when the Used CSS is cleared.

Note: the Preload will trigger Used CSS generation only for pages that aren't cached when it runs. For the rest of the pages, Used CSS generation will run when their cache is cleared and then preloaded or visited.

Therefore, you could clear the whole site's cache and run the Preload after you first enable Remove Unused CSS or when you've cleared the Used CSS.  For really large sites, you might want to avoid overloading your server and prefer to wait as eventually all pages will have the chance for the Used CSS to be generated through WP Rocket's automatic cache clearing.  

If the Preload is not enabled, for a non-cached page a visit will be required to trigger Used CSS generation. Once the used CSS is created, the cache of the page will be automatically cleared. The Used CSS will be added to a cache file, the next time there is a visit to that page.

You can also see more details in the Technical notes section of this article.


Using Remove Unused CSS with Mobile Cache

With the Mobile Cache, WP Rocket will create mobile-specific Used CSS as well as Used CSS for the desktop. Both CSS files will be stored on the server's disk in /cache/used-css/.


Using Remove Unused CSS with Preload Fonts

When Remove Unused CSS is enabled, the Preload Fonts feature will be disabled.

Instead, found fonts in the resulting Used CSS will be preloaded and inserted into the page before the CSS block.

The  display=swap property will be applied to the fonts in the resulting Used CSS.

Additionally, the data-rocket-preload attribute will be added to the preloaded fonts, to identify WP Rocket as its originator.

Finally, a font preload hint added by the Remove Unused CSS option will look like this:

<link rel="preload" data-rocket-preload as="font" href="htpps://yourdomain.com/fonts.woff2" crossorigin>

Please note, font-families that are loaded on a certain action after page load, won't be added to the resulting Used CSS. Only fonts loaded directly on page load are preserved in the Used CSS block, the ones you can see in the Network tab in  Developer Tools.

Exclude specific fonts from being preloaded

If needed, you can exclude specific fonts from being preloaded when using Remove Unused CSS. You can do this by adding this custom snippet to your site:

add_filter( 'rocket_exclude_rucss_fonts_preload', function( $fonts ) {
  //Partial match, matching all fonts under specific directory
  $fonts[]='woocommerce/assets/fonts';
  //Exact match
  $fonts[]='woocommerce/assets/fonts/font.woff2';
  return $fonts;
} );

This customization can be useful if, for example, you need to stop preloading a font that's used only on the footer of your site.

Deactivate fonts preloading

If you need this, you can use the following snippet to disable the Used CSS fonts from being preloaded:

add_filter( 'rocket_enable_rucss_fonts_preload', '__return_false' ); 

You can add this code as shown here.

Alternatively you can install the following helper plugin for that purpose:

📥  Download (.zip):  WP Rocket | Disable Used CSS Fonts Preload
Developers: You can find the code for this plugin on GitHub.


Using Remove Unused CSS with Autoptimize and Perfmatters

The Remove Unused CSS feature is automatically disabled when Autoptimize's RapidLoad Power-Up or Perfmatters' Remove Unused CSS are active on a site. In this case, the Remove Unused CSS description will show the following texts accordingly:

Automated unused CSS removal is currently activated in RapidLoad Power-Up for Autoptimize. If you want to use WP Rocket's Remove Unused CSS feature, disable the RapidLoad Power-Up for Autoptimize plugin.
Remove Unused CSS is currently activated in Perfmatters. If you want to use WP Rocket's Remove Unused CSS feature, disable this option in Perfmatters.

Automatic clearing of Used CSS

Used CSS will be automatically cleared for all pages (i.e. full Used CSS clearing) when:

  • Switching themes
  • Changing the items added to the CSS safelist text area

Used CSS will be automatically cleared for specific pages (i.e. partial Used CSS clearing) in the following scenarios:

  • Editing a post/page
  • Editing/deleting terms
  • When the comment count changes
  • 3 days after the Used CSS generation failed

The action of clearing the Used CSS will clear the cache of the pages too.

Disable automatic clearing of Used CSS

If you need to disable automatic clearing of Used CSS, you can use the following code:
add_filter( 'rocket_rucss_deletion_enabled', '__return_false' );
In most cases, it would be best to limit the above to only specific actions. For example, the following disables Used CSS clearing only when a post is updated:
add_action( 'pre_post_update', function() {   add_filter( 'rocket_rucss_deletion_enabled', '__return_false' ); }, PHP_INT_MAX);

Note: This approach is not recommended because it will prevent your site from showing the CSS changes accurately, and you'd need to manually clear the Used CSS.

When to clear Used CSS

When you make changes to stylesheets, or add/modify custom CSS via the WordPress Customizer (or a plugin), you should manually clear Used CSS via the WP Rocket toolbar menu:

Or using the Clear Used CSS of this URL button in the top bar for a specific post:

Clear Used CSS for URL

When you clear the Used CSS the existing Used CSS is removed from the disk and the cache will be cleared. 

The new Used CSS will be:

  • regenerated on the next visit to the page and
  • applied to the page on a subsequent visit.

How to exclude files from this optimization / retain selected CSS rules on a page

Files and patterns can be excluded from the option by using the CSS safelist text area on the settings page.

Safelist box

Any stylesheets and CSS selectors contained in the safelist will be added next time the Used CSS is generated.

For example, if a file is added in the text area and the file is present on the current page, its full content is added in the Used CSS.

Multiple CSS selectors

If you need to safelist a complex CSS selector like the following one:

.projects_masonry_holder.portfolio_one_by_one article.show { css declarations here... }

You can safelist all the classes in the selector, like this:

.projects_masonry_holder.portfolio_one_by_one article.show

You can also use wildcards before and/or after the selectors, as shown below:

(.*).show(.*)

Beware as using wildcards can result in too much safelisted CSS.

Finally, you can add one CSS selector per line, like this:

.projects_masonry_holder
.portfolio_one_by_one 
#pop-up

CSS attributes

To safelist CSS attributes, e.g.  title in the following example:

.my-class img[title="fancy image"] { ... }

You need to add it like this in the safelist text area:

.my-class img[title="fancy image"]

Fonts

To exclude a font you can use the @ followed by the font family's name.

For example, for:

@font-face{font-family:swiper-icons;src:('http://example.com/font/myfont.tff')}

you should add the following to the CSS safelist box:

@swiper-icons

Note: The combination of CSS/JavaScript from other plugins/themes needs to be disabled because the safelisting process uses the original CSS and JavaScript files as conditions to set the automatic safelist.


Exclude styles from being added to the Used CSS

This fix is useful in cases where certain styles should be applied under specific conditions only, and keeping them in the resulting Used CSS will break the site.

You can find more information here.


Using Remove Unused CSS with Combine CSS files

The Remove Unused CSS feature automatically disables the Combine CSS files feature, which is only available in WP Rocket versions before 3.15 .

This is because the resulting used CSS block will replace any existing CSS files, including the combined one. 


Using Remove Unused CSS with the Divi theme

WP Rocket's  Remove Unused CSS is compatible with Divi's Critical CSS.

However, Divi's  Dynamic CSS will be automatically disabled when Remove Unused CSS is enabled because they're not compatible.


Troubleshoot

If the Used CSS is not generated/applied to your page, please check the Troubleshoot Used CSS generation issues guide.

And, if the Remove Unused CSS is breaking your site's layout, you can follow the Toubleshoot Remove Unused CSS issues article.


Technical notes

  • The resulting Used CSS will be stored in the server's disk, in the /cache/used-css/1/ folder.
  • The Used CSS generation progress will be handled in the wp_wpr_rucss_used_css table.
  • The process of generating and applying the Used CSS is asynchronous, as follows:
    • Used CSS generation requires a first visit to the page, either by the Preload or a visitor.
    • The URLs will be added to the wp_wpr_rucss_used_css table.
    • The rocket_rucss_on_submit_jobs cron event will process how many URLs can be sent the generator.
    • A cron will check every 60 seconds if the used CSS for the URLs that were sent to the Used CSS generator is ready.
    • The action scheduler handles the asynchronous tasks after the visit. You may see the rocket_rucss_job_check_status hook in the main Scheduled Actions dashboard.
    • The rocket_rucss_pending_jobs cron event will send the URLs to the generator in batches.
    • The rocket_rucss_max_pending_jobs sets the maximum number of URLs that can be scheduled for optimization at any particular time.
    • You can see more information in this article.
  • In order to avoid stale content, Used CSS will be automatically cleaned and regenerated every 30 days.
  • If the resulting Used CSS is smaller than 150 bytes (150 characters), because, for example, WP Rocket's SaaS is being blocked by a security plugin or a captcha, then it will be considered as invalid CSS and WP Rocket won't apply it to your pages. In this case, your pages will keep using the original CSS. 
  • The Used CSS hash in the wp_wpr_rucss_used_css table.
  • The specific path where Used CSS is stored depends on its hash.

    Example: for a hash such as a92f2f40a719d9df1fffad70a63f1c1a the path and filename of the used CSS file will be:

    /cache/used-css/1/a/9/2/f2f40a719d9df1fffad70a63f1c1a.css.gz

    There are 3 subfolders, each one named after the first 3 letters of the hash: a, 9 and 2. The rest of the hash is used as the file's name: f2f40a719d9df1fffad70a63f1c1a
  • There will be one Used CSS entry for each cached page in the site. However, features like WebP Compatibility or Mobile Cache will have their own Used CSS entry as well.
  • One used CSS file can be shared by multiple URLs if they have the same used CSS content. They will have the same hash value in the database.
  • The Used CSS generation tool will send requests to the non-cached pages to scan the CSS, so it's expected to see server logs with the ?wpr_imagedimensions=1&nowprocket=1&no_optimize=1query string attached to the URLs.
  • The Used CSS generation requests will use the following user agents:
    • Desktop: WP-Rocket/SaaS Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36
    • Mobile: WP-Rocket/SaaS Mozilla/5.0 (Linux; Android 13; Pixel 5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Mobile Safari/537.36
Did this answer your question? Thanks for the feedback There was a problem submitting your feedback. Please try again later.