How to Fix Unused JavaScript and Speed Up Mobile Pages
PageSpeed Insights flags JavaScript that is downloaded and parsed on page load but never executed. It then estimates how many milliseconds mobile visitors would save if that code were removed. By the end of this guide you will have found the scripts responsible, removed or deferred what is not needed, split your bundles, and brought the mobile estimate under 300ms.

Why it matters
On a throttled mobile connection, every unused kilobyte of JavaScript delays first render and ties up the main thread during parsing. That pushes back Largest Contentful Paint and worsens Interaction to Next Paint, and both are Core Web Vitals that Google uses as a ranking signal. Visitors on mid-range phones also see slower, janky pages and leave sooner.
Crawlers that render JavaScript, including those used for AI answers, spend more of their budget on code that does nothing. Savings above about 1,000ms usually point to a forgotten library, an uninstalled app's leftover snippet, or a site-wide bundle that should be split.
What you need
Step-by-step fix
Measure the mobile baseline in PageSpeed Insights
g. com/) and make sure the Mobile tab is selected. Scroll to the diagnostics and expand Reduce unused JavaScript.
Note the estimated savings in ms and copy the table of script URLs with their Transfer Size and Est Savings. Repeat this for your most important templates, such as the home page, a product or article page, and a category page, because each template loads different scripts.
Confirm dead code with the DevTools Coverage tab
Open the page in Chrome and open DevTools (F12). Press Ctrl+Shift+P (Cmd+Shift+P on Mac), type Show Coverage and press Enter. Click the reload button in the Coverage panel.
Sort by Unused Bytes and filter by type JS. Click a file to see the unused lines highlighted in red in the Sources panel. A file that is 90%+ unused on a page is a candidate for removal or for loading only where it is needed.
Remove tags and plugins you no longer use
Start with the easiest wins. In Google Tag Manager, open Tags, sort by Last Edited, and pause or delete tags for retired tools, old pixels and ended experiments, then Submit and publish. In your CMS, deactivate and delete plugins or apps you no longer use.
Then search your theme for script tags that uninstalled tools left behind. Check for duplicates too: two copies of jQuery, or GA4 loaded both hard-coded and through GTM.
<!-- Search theme files for leftovers like these and delete them --> <script src="https://cdn.old-heatmap-tool.example/track.js"></script> <script src="/assets/jquery-1.12.4.min.js"></script>
Load page-specific scripts only where they are used
Scripts for sliders, maps, review widgets or checkout logic often load on every page but run on one template. Move them out of the global layout and include them only on the templates that use them. Add defer to scripts that do not need to run before the page renders.
This alone does not remove unused bytes, but it stops them from blocking rendering.
<!-- Only in the store-locator template, not in the global layout --> <script src="/js/store-map.js" defer></script>
Code-split bundles with dynamic import()
If you build JavaScript with webpack, Vite, Rollup or esbuild, replace static imports of heavy features with dynamic import(). The bundler then emits a separate chunk that downloads only when the feature is needed. Good candidates are modals, carousels, rich-text editors, charts, and anything below the fold or behind a click.
Bundlers that output ES modules split routes automatically when you lazy-load route components.
// Before: import { openVideoModal } from './video-modal.js';
const btn = document.querySelector('#play-video');
btn?.addEventListener('click', async () => {
const { openVideoModal } = await import('./video-modal.js');
openVideoModal(btn.dataset.videoId);
}, { once: true });Shrink libraries with tree-shaking and lighter swaps
Run a bundle analyzer to see what is inside each bundle. Look for these:
- Whole-library imports: replace
import _ from 'lodash'withimport debounce from 'lodash-es/debounce'. - Heavy date libraries: replace moment with the native
Intl.DateTimeFormator date-fns. - Polyfills for browsers you no longer support: update your browserslist target.
Make sure your production build uses mode: 'production' (webpack) or vite build so unused exports are dropped.
# webpack npx webpack-bundle-analyzer dist/stats.json # generate stats first: npx webpack --profile --json > dist/stats.json # Vite / Rollup npm i -D rollup-plugin-visualizer # add visualizer() to plugins in vite.config.js, then run: npx vite build
Delay heavy third-party widgets until interaction
Chat widgets, video embeds and social feeds often ship hundreds of KiB of code you cannot tree-shake. Replace them with a lightweight facade, such as a static button or thumbnail, that loads the real script only when the visitor clicks or starts interacting. Lighthouse counts the facade instead of the full widget.
<button id="chat-launcher" class="chat-btn">Chat with Example Co</button>
<script>
document.getElementById('chat-launcher').addEventListener('click', function () {
var s = document.createElement('script');
s.src = 'https://chat.example.com/widget.js';
s.onload = function () { window.ExampleChat && window.ExampleChat.open(); };
document.head.appendChild(s);
this.remove();
}, { once: true });
</script>Deploy, clear caches and re-test on mobile
Deploy the changes, then purge your CDN and any page cache plugin so PageSpeed Insights fetches the new files. Re-run PageSpeed Insights on the Mobile tab for each template you tested in step 1. Aim for estimated savings under 300ms.
Results between 300ms and 1,000ms still need work, and results above 1,000ms mean a major bundle or tag is still loading everywhere. Spot-check key flows (forms, checkout, tracking events in GA4 DebugView) to make sure nothing broke.
Platform-specific notes
WordPress
Many plugins enqueue scripts site-wide. Use a script manager to unload them per page or post type: Perfmatters (Script Manager), Asset CleanUp (Manage CSS/JS on each page), or WP Rocket (File Optimization > Delay JavaScript execution) for third-party tags. In code, call wp_dequeue_script() inside a wp_enqueue_scripts hook with a conditional such as !is_page('contact'). Since WordPress 6.3 you can pass 'strategy' => 'defer' to wp_register_script().
Shopify
Uninstalled apps often leave Liquid snippets behind. Go to Online Store > Themes > ... > Edit code, search for the app's name in layout/theme.liquid and the snippets folder, and remove the leftovers. Turn off app embeds you don't use in Online Store > Themes > Customize > App embeds. You cannot edit Shopify's own checkout or storefront scripts, so focus on theme and app code.
Next.js
Use next/dynamic for heavy client components, and load third-party scripts with next/script using strategy="lazyOnload" or "afterInteractive". With the App Router, keep components as Server Components unless they need interactivity, because 'use client' adds their code to the browser bundle. Inspect bundles with @next/bundle-analyzer (ANALYZE=true npm run build).
Webflow and Wix
You cannot change the platform's core bundles. In Webflow, review Site settings > Custom code and page-level custom code for unused embeds, and remove unused Interactions. In Wix, remove unused apps from the Apps panel and check Settings > Custom Code. Expect a floor of unused JavaScript you cannot remove on these platforms.
Cloudflare
Cloudflare Zaraz (Zaraz > Tools) can load analytics and marketing tags server-side or at the edge instead of in the browser, which takes their JavaScript out of the page. Remember to purge the cache (Caching > Configuration > Purge Everything) after deploying changes to your own bundles.
Check that it worked
✅ How to verify
- Re-run PageSpeed Insights on Mobile for each key template. The Reduce unused JavaScript estimate should be under 300ms, or the audit should appear under Passed audits.
- Reload with the DevTools Coverage panel open and confirm the total unused JS bytes dropped compared with your baseline.
- In DevTools Network, filter by JS and confirm that split chunks (e.g. video-modal.[hash].js) load only after the click or scroll that needs them.
- Check that analytics events, forms and checkout still work, using GA4 DebugView or GTM Preview mode.
⚠️ Common mistakes
- Optimizing only the home page while product, article or category templates still load the full site-wide bundle.
- Adding defer or async and assuming the problem is solved. That fixes render-blocking, but the unused bytes are still downloaded and parsed.
- Deleting a script based on Coverage alone, when the code actually runs on interaction, on another page, or for logged-in users.
- Testing before purging the CDN or page cache, so PageSpeed Insights still measures the old files.
Is this still an issue on your site? Run a free audit — ZORO checks this and 294 other SEO, AI-visibility, accessibility and security signals, with fixes for your platform.
Check my site freeFAQ
What is a good score for Reduce unused JavaScript?
Aim for estimated savings under 300ms on mobile. Savings between 300ms and 1,000ms are worth fixing. Anything over 1,000ms usually means a large library or third-party tag is loading on every page without being used.
Why does PageSpeed Insights flag Google Tag Manager or Google Analytics as unused JavaScript?
GTM and gtag.js ship code for many features, and only part of it runs on any given page. You can't trim Google's file, but you can remove unused tags and triggers in your container, avoid loading GA4 twice, or move tags server-side (for example with server-side GTM or Cloudflare Zaraz).
Is unused JavaScript the same as render-blocking JavaScript?
No. Render-blocking scripts delay the first paint because the browser waits for them. Unused JavaScript is code that downloads and parses but never runs. A deferred script can still be mostly unused, so you often need to fix both.
Will removing unused JavaScript improve my Core Web Vitals?
Usually, yes. Less JavaScript means less download and parse time on mobile, which tends to improve Largest Contentful Paint and Interaction to Next Paint. Field data in the Chrome UX Report and Search Console updates over a rolling 28-day window, so expect a delay before improvements show there.
How to Fix Third-Party Script Impact on Your Homepage
How to Fix Too Many HTTP Requests on Your Web Pages
How to Fix Web Font Loading with font-display and Preload
How to Fix Missing Lazy-Loading on Offscreen Images
How to Fix Mobile-Friendly Rendering and Horizontal Scroll
How to Fix Oversized Images and Cut Homepage Image Weight