If your speed test keeps flagging “Reduce unused CSS” and “Reduce unused JavaScript” on a WordPress site, the files behind those warnings can usually be traced and switched off page by page. The usual cause is a plugin, often a contact form, that loads its stylesheet and script on every page while you use it on one. The fix that pays off most is to unload those whole files wherever they sit idle, with a few lines of PHP or an asset manager plugin. A cache plugin’s per-page “Remove Unused CSS” feature comes afterwards, to trim what is left inside the files you keep.
What you’ll accomplish
- See, for one real page, every stylesheet and script it loads and how much of each it actually uses.
- Match each file to its WordPress handle, the short name a plugin or theme registers it under, so you can target it.
- Unload unneeded plugin files on the pages that do not use them, with code or with a plugin.
- Decide whether per-page generated CSS from WP Rocket or LiteSpeed Cache is worth adding on top.
- Confirm forms, menus and checkout still work for logged-out and logged-in visitors after the caches are purged.
Prerequisites
- WordPress 6.0 or newer, with administrator access and a staging copy if you have one.
- A way to add PHP: a small must-use plugin in
wp-content/mu-plugins/(a folder WordPress loads automatically, with no activation step) or a child theme’sfunctions.php. Avoid editing a parent theme, because its next update overwrites your changes. - Chrome or Edge for the DevTools Coverage tab. Firefox has no equivalent panel.
- The free Query Monitor plugin, which adds a debugging menu to the admin toolbar. Install it on staging, or limit it to your own account on production.
- Access to purge every cache in front of the site: the cache plugin, any server cache, and the CDN (content delivery network) if you use one.
How it works
WordPress builds each page’s list of files from handles. A plugin calls wp_enqueue_style() or wp_enqueue_script(), usually during the wp_enqueue_scripts action, and WordPress prints a <link> or <script> tag for every handle still in the queue when the page is output. Many plugins enqueue their files unconditionally, because detecting whether a form or slider appears on a given page is harder than loading it everywhere.
Two kinds of waste show up, and they need different tools.
The blue group is whole files the page never needs. Removing them saves the download and the parse time, and it works for JavaScript as well as CSS. This is what dequeuing does: you take the handle out of the queue before WordPress prints it, only on the pages where it is useless.
The amber rows are files the page needs partly. The combined block library stylesheet, which WordPress core registers as wp-block-library, holds rules for every core block, while one post might use five of them. You cannot unload it without breaking those five blocks. This is where WP Rocket’s “Remove Unused CSS” or LiteSpeed Cache’s UCSS (short for “unique CSS”, a stylesheet built for one URL) comes in. Those features scan each page’s HTML and generate a smaller stylesheet holding only the rules that page matched. They only handle CSS and they need regenerating as content changes, so they work best after the whole-file cleanup.
Unloading a file is a separate job from loading it later. Deferring scripts and inlining critical CSS still download the file, only at a better moment. Those techniques are covered in defer, async and minify for WordPress JavaScript and critical CSS for WordPress.
Step-by-step
-
Pick three page types to audit. Choose your most visited content page (usually a blog post), the homepage, and the page that holds your form or shop. Assets that load on the first but are only used on the third are your targets.
-
Measure with the Coverage tab. Open the blog post in a private window, so you see what a logged-out visitor gets. Open DevTools, press
Ctrl+Shift+P(Cmd+Shift+Pon a Mac), type “coverage”, and choose Show Coverage. Click the reload button inside the Coverage panel so it records the page load from the start.Expected result: a list of URLs with Type, Total Bytes, Unused Bytes and a usage bar. Sort by Unused Bytes. Plugin files with almost all of their bytes unused are your first candidates. If the list is empty, you clicked the record button without reloading; click the reload button inside the panel instead.
-
Confirm the requests in the Network panel. Switch to the Network tab, reload, and type a plugin’s folder name, such as
contact-form-7, in the filter box. Every row that remains is a request this page makes for that plugin. Note the file paths, because the next step turns them into handles. -
Find the handle in Query Monitor. Visit the same page while logged in and open Query Monitor from the admin toolbar. The Styles and Scripts panels list every handle on that request, with its source URL, its dependencies, and the handles that depend on it. Match each wasteful file path to its handle.
Expected result for Contact Form 7: a style and a script, both with the handle
contact-form-7. The script also pulls inswv, the plugin’s form validation script, and core’swp-i18nas dependencies. You do not need to target those, because a dependency only prints when something in the queue still asks for it. Ignoreadmin-baranddashiconshere; they load only because you are logged in and the toolbar is showing.You can also read handles from the HTML. WordPress prints each stylesheet with an
idmade of the handle plus-css, and each script with the handle plus-js:curl -s https://example.com/blog/sample-post/ | grep -oE "id=['\"][a-z0-9_-]+-(css|js)['\"]"Example output:
id='wp-block-library-css' id='contact-form-7-css' id='theme-style-css' id="wp-hooks-js" id="wp-i18n-js" id="swv-js" id="contact-form-7-js" id="theme-navigation-js"The mixed quotes are normal: WordPress prints stylesheet tags with single quotes and script tags with double quotes. If this prints nothing, you are probably getting a cached or optimized copy where a plugin has combined files. Repeat the check on staging with file combining switched off.
-
Write the dequeue rule in a must-use plugin. Create
wp-content/mu-plugins/asset-trim.php. The example keeps Contact Form 7 on pages whose content contains its shortcode, plus two named pages, and removes it everywhere else:<?php /** * Plugin Name: Asset trim * Description: Unloads plugin assets on pages that never use them. */ add_action( 'wp_enqueue_scripts', 'sh_trim_unused_assets', 100 ); function sh_trim_unused_assets() { $post = get_post(); $has_form = is_singular() && $post && has_shortcode( $post->post_content, 'contact-form-7' ); // Pages that show a form outside the post content (template, widget). $form_pages = array( 'contact', 'request-a-quote' ); if ( ! $has_form && ! is_page( $form_pages ) ) { wp_dequeue_style( 'contact-form-7' ); wp_dequeue_script( 'contact-form-7' ); } }Three details make this work. Priority
100runs the function after plugins have enqueued at the default priority of 10; at priority 10 it might run first and remove nothing. The condition depends only on the page, never on the visitor, so a page cache stores the same HTML for everyone. Andwp_dequeue_*only removes the item from the queue, so if another enqueued script listscontact-form-7as a dependency, WordPress pulls it back in. When that happens, Query Monitor’s Dependents column names the script responsible.If a form sits in the footer or a sidebar on every page, it is used sitewide. Leave it loaded.
-
Use
wp_deregister_*only to replace a file.wp_deregister_script()deletes the handle’s registration entirely. Any script that depends on that handle then stops printing as well, which is useful when you register your own copy under the same name and harmful otherwise. For unloading on selected pages, dequeue is the right call. -
Or use an asset manager plugin instead of code. Asset CleanUp and the Script Manager in Perfmatters both list the files a page loads. You can switch each one off for that URL, for a post type, or sitewide with exceptions. They do the same dequeue behind the scenes, with a screen instead of PHP. Pick one route per site. Rules written in two places are hard to debug, because a file can disappear and nobody knows which rule removed it.
-
Purge every cache, then re-measure. Clear the cache plugin, the server cache and the CDN, in that order. Then rerun the
curlfrom step 4 on the blog post and on the contact page.Expected result: no
contact-form-7orswvlines on the blog post, and all of them still present on the contact page. If the blog post still shows them, the HTML came from a cache you did not purge, or the plugin enqueues later thanwp_enqueue_scripts; see Troubleshooting. -
Decide on per-page generated CSS last. With the whole-file waste gone, rerun Coverage. Start with the block library, because core can fix it without any generated files. If Coverage still lists the full
block-library/style.min.css, addadd_filter( 'should_load_separate_core_block_assets', '__return_true' );to your must-use plugin. WordPress then swaps the combined file for small per-block stylesheets and loads only those for blocks the page renders. Block themes already do this by default, and so do classic themes from WordPress 6.9 onwards. On a classic theme with an older WordPress, those block styles print near the end of the page, so reload a few posts and watch for a brief flash of unstyled content.If the theme’s own stylesheet still shows mostly unused bytes after that, consider a generated per-page stylesheet. In WP Rocket that is Remove Unused CSS, in the Optimize CSS delivery section of File Optimization. In LiteSpeed Cache it is Generate UCSS, on the CSS Settings tab of Page Optimization. Turn it on in staging first. Classes that JavaScript adds after page load, such as an open menu or a modal, may be missing from the scan. List them in WP Rocket’s CSS safelist or LiteSpeed’s UCSS Selector Allowlist.
Validate it works
Run through this list on staging, then again on production after the purge:
- Logged out, in a private window: submit the contact form for real and confirm the success message and the email arrive. Open the mobile menu, any slider, and any modal.
- Logged in as an editor: load the same pages. Some plugins enqueue different files for logged-in users, and the admin toolbar adds its own.
- Browser console: with DevTools open, reload each test page and look for red
ReferenceErrororTypeErrormessages. A message naming a function from a plugin you trimmed means another script still expects it on that page. - Shop pages, if WooCommerce runs: add to cart, open the cart, and reach the payment step. Do not dequeue WooCommerce scripts on cart, checkout or account pages. The
wc-cart-fragmentsscript deserves its own decision, because removing it changes how the mini-cart refreshes. - The numbers: repeat the Coverage recording on the blog post. The unloaded files should be gone from the list, and the total bytes for the page should drop by about their size.
Troubleshooting
The file still loads after the dequeue. First, check the HTML with curl after a full purge, because a cached page hides any change. If it really is still there, the plugin enqueues later than your hook. Some plugins enqueue from inside their shortcode or widget output. A script that is enqueued late prints in the footer, so you can also dequeue it by hooking wp_print_footer_scripts at priority 5, before WordPress prints the footer scripts.
The handle name is wrong. Handles are case-sensitive and often differ from the folder name. Copy them from Query Monitor rather than guessing from the URL.
A form or slider breaks on one page only. Your condition missed that page. The form is often in a template, a widget, or a page builder layout rather than the post content, so has_shortcode() cannot see it. Add the page to the allow list, or use a condition based on the template, such as is_page_template().
Styling breaks only after you turn on generated CSS. That points at the generated stylesheet, not at your dequeue rules. Switch the feature off on staging and confirm the page looks right with your rules alone. Then turn it back on and add missing selectors to the safelist; for WP Rocket, the steps are covered in fixing common WP Rocket issues.
When this is the wrong approach
- Your bottleneck is elsewhere. If server response time, unoptimized images, or third-party tags dominate your report, trimming a 12 KB stylesheet will not move the score much. Fix the largest item first.
- The plugin is used almost everywhere. A file that half your pages need is cheaper to keep and let the browser cache than to manage with fragile per-page rules.
- Nobody will maintain the rules. Every new page that uses a form must be added to the allow list. If editors add forms often, prefer a condition that detects the form, or an asset manager plugin with post-type rules they can see.
- The plugin offers its own switch. Some plugins have a setting or filter that controls where their assets load. Contact Form 7, for example, stops loading its script and stylesheet everywhere when the
wpcf7_load_jsandwpcf7_load_cssfilters returnfalse. You then callwpcf7_enqueue_scripts()andwpcf7_enqueue_styles()from the templates that show a form. Use the built-in option when it covers your case.
The official references for the functions used here are the WordPress Developer Resources pages for wp_dequeue_script() and the Chrome DevTools Coverage panel.
Running WordPress that earns real money deserves an operator — Stack Harbor runs that stack under Enterprise WordPress; book an infrastructure consult.