Check 06.11 · Performance and Core Web Vitals

Remove unused CSS/JS

Measure unused CSS and JavaScript with Chrome's Coverage tool, then remove, split or load on demand the code the page does not need.

Priority
Important
Difficulty
Advanced
Estimated time
1 to 5 days
Free, no account: your progress is saved in this browser.

Ask an AI to check this point on your site

Opens the assistant with a ready-made question: this check, its goal and your site URL.

For Gemini, Copilot or another assistant, copy the question. The link opens the chosen service directly: nothing goes through this site.

In short

A page often loads far more CSS and JavaScript than it uses: a stylesheet shared by the whole site, entire libraries for a single function, plugin scripts active everywhere. The task is to measure this surplus, remove what is no longer used anywhere, then load on each page only the code it needs. The expected result: lighter files and a less busy main thread, not a 100% usage rate.

Why it matters

Unused code has a cost even if it never runs.

  • CSS: the browser has to download and parse every stylesheet in the head before displaying anything. A rule that applies to no element is still read and matched against the DOM.
  • JavaScript: each file is downloaded, parsed and compiled, even if none of its functions is called. On a mid-range phone, this step keeps the main thread busy and delays interactions.

The surplus builds up naturally: a plugin installed for one page, a removed component whose styles stayed behind, a polyfill for a browser that has disappeared, a date library with several hundred functions used for two of them.

What it improves

  • LCP (Largest Contentful Paint, rendering of the largest visible element) Smaller render-blocking CSS lets the page display sooner.
  • INP (Interaction to Next Paint, responsiveness to interactions) Less JavaScript to parse and run, so a more available main thread. This is often the clearest gain.
  • Page weight Less data, which matters on mobile networks.
  • Rendering by crawlers Googlebot runs JavaScript with limited resources; less code reduces the risk of incomplete rendering. The effect is indirect.
  • Maintenance Fewer dependencies to update and monitor.
  • Rankings No direct effect; a contribution to Core Web Vitals.

How to check

Chrome's Coverage tool:

  1. Open DevTools, then the Command Menu (Ctrl+Shift+P or Cmd+Shift+P) and type “Coverage”.
  2. Click the reload button in the Coverage tab.
  3. Read the table: for each file, the total size, the unused bytes and a red and blue bar. Click a row to see the code that did not run, highlighted in the Sources tab.

Lighthouse and PageSpeed Insights list the files concerned in the “Reduce unused CSS” and “Reduce unused JavaScript” diagnostics, with the estimated savings.

Warning: Coverage measures one page, in one state, at one moment. A style that is “unused” at load time may be needed on hover, in an open menu, a modal window, a form error message or on another template. Never remove a rule based on this table alone.

A common-sense benchmark: look first for files that are more than half unused and files that are entirely unused on a template. Those are the ones that pay off.

How to implement

Step 1 — Measure by template

Run Coverage on one URL per template, at mobile width, and note for each file its weight, its unused share and its origin (theme, plugin, library, third party).

File Weight Unused (home) Unused (product page) Origin Decision
slider.js 85 KB 100% 100% Old slider Remove
app.css 240 KB 82% 74% Theme Purge and split
carte.js 160 KB 100% 100% Contact page only Load on the contact page

Step 2 — Remove what is no longer used anywhere

This is the lowest-risk gain. Look for:

  • libraries for a removed component (slider, modal window, animation);
  • disabled plugins and modules whose files are still loaded by the theme;
  • complete icon fonts used for three icons: replace them with SVGs;
  • polyfills for browsers nobody uses any more;
  • marketing tags from campaigns that have ended: see limit third-party scripts (opens in a new tab).

Step 3 — Load per page what only one page needs

The map script has no business on the home page. Two techniques:

  • conditional loading on the server side: include the script or link tag only in the template concerned;
  • dynamic import: only download the module when the visitor needs it.
document.querySelector('#ouvrir-carte').addEventListener('click', async () => {
  const { afficherCarte } = await import('./carte.js');

  afficherCarte(document.querySelector('#carte'));
});

Build tools (Vite, webpack) automatically create a separate file for each dynamic import.

Step 4 — Purge the CSS

A purge tool compares your stylesheets with your templates and removes selectors it cannot find. With PostCSS and PurgeCSS, in postcss.config.mjs:

import { purgeCSSPlugin } from '@fullhuman/postcss-purgecss';

export default {
  plugins: [
    purgeCSSPlugin({
      content: ['./templates/**/*.html', './resources/views/**/*.blade.php', './resources/js/**/*.js'],
      safelist: [/^is-/, /^has-/, 'active', 'open'],
    }),
  ],
};

From the command line, without a build tool:

npx purgecss --css public/css/app.css --content "templates/**/*.html" "public/js/**/*.js" --output public/css/purge/

The import syntax has changed between major versions of PurgeCSS: check the one for the installed version.

Two precautions: list in content every file that contains class names, including JavaScript, and put in safelist the classes added dynamically (states, classes coming from the CMS or a content editor). Then visually compare each template before and after.

Tailwind CSS only generates the classes it finds in your files: with it, there is no purge to add, but the same precautions apply to dynamically built classes.

Step 5 — Reduce bundled JavaScript

First visualize what the bundle contains (the second command requires source maps):

npx vite-bundle-visualizer
npx source-map-explorer "public/build/assets/*.js"

Then:

  • import only what you use, so that the build tool removes the rest (tree shaking):
import debounce from 'lodash-es/debounce';
  • replace heavy libraries with native APIs: Intl.DateTimeFormat for dates, fetch for requests, querySelector and classList instead of jQuery for simple manipulations;
  • target current browsers in the browserslist configuration so you no longer transpile or load unnecessary polyfills;
  • split by route: one entry point per template rather than a single file.

WordPress

Versions WordPress 6.0 to 7.1; LiteSpeed Cache 7.x; Perfmatters, Asset CleanUp and WP Rocket in their November 2026 versions.

Each plugin registers its files on every page, even when it only acts on one.

Remove them where they are not needed, in the child theme's functions.php file or in a custom plugin:

add_action('wp_enqueue_scripts', function (): void {
    if (is_page('contact')) {
        return;
    }

    wp_dequeue_style('contact-form-7');
    wp_dequeue_script('contact-form-7');
}, 100);

The registration handle of each file (here contact-form-7) can be read in the page source: it is the tag's id attribute, without the -css or -js suffix.

Without code:

  • Perfmatters (Script Manager) or Asset CleanUp: disable files per page, per content type or everywhere except for exceptions;
  • WP Rocket (Remove Unused CSS option) and LiteSpeed Cache (unique CSS per page, through the QUIC.cloud service): automatic generation of a reduced CSS per page. Check each template after enabling it;
  • start by removing unnecessary plugins (opens in a new tab): it is more effective than filtering their files.

Block themes only load the styles of the blocks present on the page; page builders usually offer an equivalent option in their performance settings.

Shopify

Versions Online Store 2.0 themes, Shopify admin, November 2026.

  • Uninstalling an app does not always remove its code from the theme: look for its snippets in theme.liquid and in the snippets folder, and delete them.
  • In the theme editor, disable the app embeds you do not use.
  • Load a section's CSS and JavaScript in the section itself rather than in theme.liquid, so that they are only present on pages that use it.

PrestaShop

Versions PrestaShop 8 and 9.

In the Module Manager, uninstall unused modules: a module that is merely disabled no longer loads its files, but still needs maintaining. In Design > Positions, unhook a module from the pages where it adds nothing. Then clear the cache in Advanced Parameters > Performance.

Laravel

Versions Laravel 10 to 13, with Vite and laravel-vite-plugin.

With Vite, declare one entry point per need rather than a global file:

// vite.config.js
import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';

export default defineConfig({
  plugins: [
    laravel({
      input: ['resources/css/app.css', 'resources/js/app.js', 'resources/js/carte.js'],
    }),
  ],
});

Then, in the one view concerned:

@push('scripts')
    @vite('resources/js/carte.js')
@endpush

The main layout must contain @stack('scripts') before the closing body tag.

Next.js

Versions Next.js 15 and 16 (App Router).

Splitting by route is automatic. What remains are heavy components and dependencies:

import dynamic from 'next/dynamic';

const Carte = dynamic(() => import('./Carte'), {
  loading: () => <p>Loading map…</p>,
});

Keep as Server Components everything that does not need interactivity: their code is not sent to the browser. To find out what the bundles contain, the analysis tool depends on the version and the bundler.

Next.js 16.1 and later (Turbopack)

Turbopack has been the default bundler since Next.js 16. The built-in analyzer opens an interactive view, filterable by route, that shows each module's size and the import chain that brought it into the bundle:

npx next analyze

The --output option saves the analysis to .next/diagnostics/analyze, so you can compare before and after an optimization. In the first 16.x versions, the command was called next experimental-analyze.

Next.js 15 or webpack build

Install the @next/bundle-analyzer plugin, then wrap the configuration in next.config.js:

const withBundleAnalyzer = require('@next/bundle-analyzer')({
  enabled: process.env.ANALYZE === 'true',
});

module.exports = withBundleAnalyzer({});

Run ANALYZE=true npm run build: the report opens in the browser.

Astro

Versions Astro 5 to 7.

Astro ships no JavaScript by default. For an interactive component, choose the latest possible directive: client:visible only loads the code when the component comes into view, client:idle when the browser is idle.

Common mistakes

  • Removing a rule because Coverage marks it red on one page: it may be needed on hover, on mobile or on another template.
  • Purging without a safelist: classes added by JavaScript or by editorial content disappear, and the defect only shows up in production.
  • Aiming for zero unused bytes: a CSS file shared by the whole site, cached once, is often better than a different CSS file per page.
  • Generating a CSS file per page without watching the cache: each page then downloads its own file and the browser cache no longer helps.
  • Removing a polyfill without looking at your audience: check your visitors' actual browsers in your analytics tool.
  • Importing an entire library for one function: import _ from 'lodash' bundles everything.
  • Forgetting third-party scripts: they often account for the largest share of unused JavaScript, and no build tool reduces them.

Frequently asked questions

How do I find a page's unused CSS and JavaScript?

In Chrome, open DevTools, type “Coverage” in the Command Menu and reload the page: the table gives each file's size and the share of unused bytes, and the code that did not run is highlighted in the Sources tab. Lighthouse and PageSpeed Insights also list the files concerned with the estimated savings. Measure one URL per template, at mobile width.

Can I remove all the CSS flagged as unused?

No. The Coverage tool measures one page, in one state, at one moment. A rule marked as unused at load time may be needed on hover, in an open menu, a modal window, a form error message or on another template. First remove files that are no longer used anywhere, then purge with a safelist and visually compare each template before and after.

Should I aim for 0% unused code?

No. A CSS file shared by the whole site, cached once, is often better than a different file per page that the browser cache cannot reuse. Look for the big gains first: files more than half unused, libraries loaded everywhere for a single page, plugins active across the whole site, and third-party scripts, often the largest share of unused JavaScript.

How do I remove a WordPress plugin's CSS and JavaScript where it is not needed?

In the child theme's functions.php, call wp_dequeue_style and wp_dequeue_script with the file's registration handle, except on the pages concerned. The handle can be read in the tag's id attribute, without the -css or -js suffix. Without code, Perfmatters or Asset CleanUp disable files page by page. Start, however, by removing plugins that are no longer used.

Updated on

Topic checklist (PDF)

And now?

In the “Performance and Core Web Vitals” topic

  1. Analyze PageSpeed Insights and Lighthouse
  2. Analyze real-user CrUX data
  3. Target LCP ≤ 2.5 s at the 75th percentile
  4. Target INP ≤ 200 ms at the 75th percentile
  5. Target CLS ≤ 0.1 at the 75th percentile
  6. Target TTFB ≤ 800 ms as a benchmark
  7. Optimize hosting and CDN
  8. Enable Brotli/Gzip
  9. Configure browser and server caching
  10. Minify CSS and JavaScript
  11. Remove unused CSS/JS
  12. Reduce render-blocking resources
  13. Defer non-essential scripts
  14. Limit third-party scripts
  15. Optimize database queries
  16. Optimize fonts (WOFF2, font-display)
  17. Preload only critical resources
  18. Optimize the LCP image without lazy loading
  19. Lazy-load offscreen content
  20. Reserve space for media and ads
  21. Reduce DOM complexity
  22. Test before and after cookie consent
  23. Test on a slow mobile connection
  24. Set a performance budget
  25. Preload likely navigations with Speculation Rules
  26. Make pages eligible for the back/forward cache (bfcache)
  27. Diagnose INP with Long Animation Frames (LoAF)