Reduce unused JavaScript: load only what each page uses

Lighthouse lists the scripts your page downloads and doesn't run while it loads. What they do to your visitors, and how to load each one only where it is needed.

Arjen Karel
Updated · 8 min read
Share

Why does Lighthouse say Reduce unused JavaScript?

Reduce unused JavaScript (Remove unused JavaScript in older versions) lists every script with more than 20 KiB of code that didn't run while your page loaded, and tells you to defer loading scripts until they are required. When those scripts download alongside your main photo, they slow it down. Load each script only on the pages that use it, and load code for a tap when the visitor taps.

Just want the quick fix? Jump to WordPress, Google Tag Manager and other tags, Shopify or Next.js and your own build.

What does Lighthouse count as unused JavaScript?

The full notice reads: "Reduce unused JavaScript and defer loading scripts until they are required to decrease bytes consumed by network activity."

Lighthouse report, Reduce unused JavaScript in red with Est savings of 151 KiB and the labels FCP, LCP and Unscored; under acme-yoga.test with the label 1st Party the theme's theme.min.js with 116.1 KiB est savings and five library lines under it (plyr, glightbox, flatpickr, swiper, gsap ScrollTrigger), and a map plugin's leaflet.js with 34.7 KiB

Lighthouse as PageSpeed Insights runs it, on a yoga studio's site: the theme's bundle and a map plugin's script.

While Lighthouse loads your page, Chrome records which functions in each script run. Code that didn't run in that one load counts as unused, including the code for things that only happen when a visitor taps or scrolls: the mobile menu, a date picker, the cart. A script is listed when more than 20 KiB of it, compressed, didn't run.

Lighthouse groups the scripts by owner: your own domain as "1st Party", a vendor's files under its name. Transfer Size is the size of the download; Est Savings is the part that didn't run. With a source map, Lighthouse names the libraries inside a bundle on the lines under it.

Red means a listed script downloads before your largest element (LCP) has loaded, so a smaller download would show that element sooner. Orange means the script only adds kilobytes, usually a tag that arrives after the LCP. Unscored: the notice itself doesn't count toward the Performance score, but LCP does, and Google ranks on what your real visitors get.

What does unused JavaScript do to your visitors?

Your visitor waits longer for the photo at the top of the page and for the slider, the menu and the buttons to work. The browser downloads every byte of a script, also the part that never runs, and those bytes share the phone's connection with the photo and with the scripts the page does need.

I measured this on a yoga studio's site whose page-builder theme loads a slider, a lightbox, a video player, a date picker and animations on every page, and a map plugin adds its own script. The home page uses the slider and the menu; after the fix it loads the code for just those, and the date picker when the visitor taps the booking button. Both ran on one slow phone connection and a mid-range phone's processor:

Yoga pageJavaScript downloadLCP photoSlider and menu work
Before199 kB2.03 s2.07 s
After26 kB1.15 s1.16 s
Phone screen 1.5 seconds after the tap, before the fix: the yoga studio's heading and booking button on a plain dark background, no photo yet

Before

The same moment after the fix: the photo of a yoga class behind the heading and the booking button

After

The yoga page 1.5 seconds after the visitor tapped the link.

Code that never runs takes the processor very little time, because the browser only skims it: before the fix the processor needed about 40 ms more for the scripts, and the rest of the 0.9 seconds was download. According to the State of Web Vitals, about half of the JavaScript on the median home page has not run by the time the page has loaded.

Unused code for the mobile menu belongs on the page, because the menu has to work on the first tap; a map script on a page without a map is waste.

Whose script is Lighthouse pointing at?

The file's address tells you who decides about it and what you can do. On WordPress, the folder after /wp-content/plugins/ is the plugin's name, and /wp-content/themes/ is your theme.

  • Your theme or page builder: a bundle in your theme's folder, or the builder's own files, such as Elementor Pro's elements-handlers.min.js, Lottie and the Swiper slider (WordPress).
  • A plugin that brings a big library: with its reCAPTCHA integration on, Contact Form 7 loads Google's reCAPTCHA on every page, and the Stripe gateway for WooCommerce loads Stripe.js on every product and cart page.
  • Tags, listed under the company's name: Google's gtag.js (about 150 KiB per tag ID), Meta Pixel, cookie banners such as OneTrust and chat widgets such as Intercom (tags).
  • Shopify's files and your apps: the Web Pixels Manager (/cdn/wpm/…) is listed on every Shopify store, and because it comes from your store's own domain it looks like part of your theme. Apps such as Yotpo load from the app maker's domain (Shopify).
  • Your app's own chunks: in Next.js or Nuxt, chunks that are almost all code for later, such as components that show after a tap or a whole icon set (Next.js and your own build).
Lighthouse report, Reduce unused JavaScript in orange with Est savings of 99 KiB: only gtag.js from www.googletagmanager.com, listed under Google Tag Manager, 154.1 KiB transfer size and 99.0 KiB est savings

The yoga page after the fix, with one Google tag: one orange line under Google Tag Manager.

Which part of a script ran? Coverage in DevTools

The report gives a number per file; the Coverage panel in Chrome DevTools shows which code inside it ran. Open DevTools, press Ctrl+Shift+P (Cmd+Shift+P on a Mac), type "Show Coverage" and click the reload button in the panel. Sort by "Unused bytes": in the bar, grey didn't run and green did. A bundle with a source map opens into its libraries, and a click on a row shows the lines in the Sources panel.

Chrome DevTools Coverage panel, per function: the theme's theme.min.js with 493,999 total bytes and 373,557 unused bytes (75.6%), opened into its libraries: plyr 91.2% unused, glightbox 88%, flatpickr 98.7%, gsap ScrollTrigger 83.5%, swiper-core 43.5%

Coverage on the yoga page before the fix: three quarters of the theme's bundle didn't run, and of the date picker almost nothing ran.

Coverage keeps recording while you use the page: open the menu or a form to see the code to load on the tap. Without DevTools, the View Treemap button in the Lighthouse report and in PageSpeed Insights shows every script by size, with the unused bytes of each.

How do you fix Reduce unused JavaScript?

Start with the largest file you control. The defer attribute (WP Rocket's "Load JavaScript deferred") changes when a script runs; the file still downloads during the load and stays listed.

WordPress

  • Unload a plugin's script where it isn't used: with Asset CleanUp (menu "Asset CleanUp", "CSS & JS Manager") or the Script Manager in Perfmatters you switch a script off per page, per post type or everywhere except a few pages. Turn on their test mode first, so only you see it. Never unload a file other scripts need, such as jQuery or wp-polyfill: WordPress then drops every script that depends on it, and on a store that can be the cart.
  • Use the page builder's own setting: in Divi, "Dynamic JavaScript Libraries" (Theme Options, General, Performance); in Slider Revolution, switch off "Load JS Libraries Globally". In Elementor, every Pro widget with JavaScript, such as Lottie or a carousel, adds code: use fewer, above all in a Theme Builder header, which is on every page.
  • Weigh a plugin against what it does: Contact Form 7 with its reCAPTCHA integration loads 359 KB on every page to stop some spam on one form. Lighter ways keep bots out of a form: a hidden field that only bots fill in, or a check on the server.

"Delay JavaScript execution" in WP Rocket, and the same setting in Perfmatters, LiteSpeed Cache or FlyingPress, clears the notice because Lighthouse never taps or scrolls. Your visitor still downloads and runs all that code, as soon as they tap or scroll. A "combine JavaScript" setting puts the same unused code in one larger file.

Elementor's Improved Asset Loading, which older guides send you to, has been built in since version 3.26. Check the list again after an update or a new plugin: an update can rename a script, and a new plugin can bring jQuery back to every page.

Google Tag Manager and other tags

Every Google tag ID on the page downloads its own copy of gtag.js. Several Google tags on one page are a setup to rethink: a slower site sells less, so whoever adds a tag answers for what it does to the speed. Ask who still uses each tag, and pause or remove the rest in Google Tag Manager. A tag with a trigger exception still downloads with the container.

Tags that don't earn money can wait: load them after the page has loaded, or when the browser is idle after that, so the page, the cart and the checkout come first. In Google Tag Manager that is the "Window Loaded" trigger for those tags. On WordPress, WP Core Web Vitals does this for analytics, pixels and chat widgets. A chat widget or a video player can wait for a click on its button.

Shopify

Leave the line for Shopify's own Web Pixels Manager and change the apps:

  • Remove the apps you no longer use, and switch off their app embeds in the theme editor (App embeds).
  • An app removed from the store can leave its code in the theme. Search layout/theme.liquid and the snippets folder for the app's name or domain, and remove the lines that load its script.
  • A review app that loads on every page and shows only on product pages: ask the vendor to load it only there.

The accelerated checkout buttons (Shop Pay, Apple Pay, Google Pay) load Shopify's wallet scripts. They usually stay because they sell, but they add their download to every page that shows the buttons.

Next.js and your own build

Split off what the first screen doesn't need. A component that shows after a tap, such as a date picker or a search box, loads with next/dynamic, React.lazy or a plain import(), which your bundler turns into a separate file. On the yoga page, the date picker now downloads when the visitor taps "Book a free trial class":

document.querySelector('#book').addEventListener('click', async () => {
  const { default: flatpickr } = await import('flatpickr');
  flatpickr('#date', { inline: true });
}, { once: true });

The wait moves to the tap: on the yoga page the date picker took 0.35 seconds to appear instead of 0.09. Start the download when the button scrolls into view, or once the page has loaded and the browser is idle, and the tap has nothing to wait for.

  • Libraries that only render, such as syntax highlighting or charts, belong in a Server Component in the Next.js App Router: the browser gets the result and none of the library.
  • Packages with many exports: import { debounce } from 'lodash' brings about 27 KB of lodash; lodash-es brings 2 KB. For icon and component libraries, list them under experimental.optimizePackageImports in next.config.js.
  • Find what fills a bundle with npx next analyze (Next.js 16.1 and newer) or @next/bundle-analyzer for webpack.

How do you check the change worked?

Run Lighthouse again the same way and open Coverage. Then tap everything you split off or unloaded: the menu, the forms, the cart and the checkout.

CoreDash, LCP subparts for images on mobile at p75: a donut and four phases, Time To First Byte, Load Delay, Load Time in purple with the label Improve, and Render Delay

The LCP breakdown on mobile in CoreDash. Load Time is the time the browser spends downloading your LCP photo.

Scripts that share the connection make Load Time longer for your real visitors, so look for it to get shorter on the pages you changed. Search Console takes up to 28 days to show the change.

When can you leave a line in this list?

A line can stay when the script is worth its download to you. Leave Shopify's Web Pixels Manager, the one Google tag you use when it loads after the page, and code for a tap such as the cart. Fix what you control when the notice is red, and every file for something the page doesn't have.

Some lists hold fifteen files from six vendors, and nobody knows which tags and plugins are still in use. In a power hour we open your report and your tag setup and decide which scripts stay, and on which pages.

About the author

Arjen Karel is a web performance consultant and the creator of CoreDash, a Real User Monitoring platform that tracks Core Web Vitals data across hundreds of sites. He also built the Core Web Vitals Visualizer Chrome extension. He has helped clients achieve passing Core Web Vitals scores on over 925,000 mobile URLs.

Arjen Karel

Need a faster site?

I'm Arjen, and I've been fixing slow sites for 17 years. If you're running into issues you can't fix yourself, send me your URL and let's have a chat.

Send me your URL
Arjen Karel
Arjen Karel, Web performance consultant since 2009

Why isn't our fix working?

Sometimes the CDN still serves the old HTML, or the fix went into the desktop template and mobile uses another one. Send me your URL and the problem, and I reply with a few times. I check your field data first, then we spend one hour on your site, and within a day you have my notes in writing. €350 excl. VAT.

Send me your URL

No developer to build the fix? I do the work myself, on a copy of your site.

Arjen KarelCore Web Vitals still red on mobile?Send me your URL