How To Remove Unused JavaScript In WordPress (PageSpeed Item)

When testing your site in PageSpeed Insights, you may come across a recommendation to remove unused JavaScript.

In WordPress, you can remove unused JavaScript from specific pages/posts using the Asset CleanUp or Perfmatters plugin. Sometimes, JavaScript files can also be from third-party code.

A good starting point is to check your GTmetrix Waterfall chart to see where JavaScript is being loaded. This way, you can narrow down whether it’s from your website or a third-party source. For third-parties, try hosting files locally, delay loading them, or use browser hints like prefetch.

Most WordPress sites that need to remove JavaScript use heavy page builders like Elementor or Divi. I replaced Elementor with Gutenberg and my site is much faster since it doesn’t load all that extra CSS and JavaScript. GeneratePress and Genesis Framework are also lightweight, but I recommend viewing your source code and seeing how many times your page builder shows up.

Remove Unused JavaScript WordPress

 

1. Find the source of heavy JavaScript files

Open your GTmetrix Waterfall chart and view the JavaScript tab. Look at each JavaScript file and it’s source + load time.

  • Is it jQuery?
  • Is it third-party JavaScript?
  • Is it your theme’s JavaScript files?

This should help you narrow down where your heaviest JavaScript files are. From my experience, most heavy JavaScript files come from page builders, third-party code (i.e. advertisements), and plugins. The next steps will help you reduce JavaScript in WordPress.

GTmetrix Waterfall JavaScript Files
Find heavy JavaScript files in your GTmetrix Waterfall chart

 

2. Choose an asset unloading plugin

Asset CleanUp (free) and Perfmatters (paid) let you disable unused JavaScript.

Asset CleanUp also has a pro version which lets you unload custom CSS, while Perfmatters does not. However, I use Perfmatters because the UI/UX is much easier than Asset CleanUp. Asset CleanUp has a Test Mode which lets you test disabling JavaScript without breaking your site, while Perfmatters does not. I wrote a comparison of the two – choose the one best for you.

Perfmatters-vs-Asset-CleanUp

 

3. Remove unused JavaScript

Now it’s time to learn which scripts and plugins load across your entire WordPress site, but are only used in certain areas. This is common with contact form plugins, social sharing plugins, tables, sliders, rich snippets, comment plugins, and JavaScript in page builders like Elementor.

Step 1: Install Asset CleanUp Or Perfmatters

I prefer Perfmatters over Asset CleanUp because it lets you disable plugins everywhere except pages and posts, and because Asset CleanUp only lets you disable plugins everywhere except pages. Perfmatters is also known for being user-friendly.

Step 2: Enable Test Mode If Using Asset CleanUp

Asset CleanUp Test Mode

Step 3: Enable The Script Manager If Using Perfmatters

Perfmatters-Script-Manager-Toggle

Step 4: Disable JavaScript Files Where They Don’t Need To Load

Remove Contact Form JavaScript
Disabling contact form plugin everywhere except contact page (using Asset CleanUp)
Disable Plugins Perfmatters
Disable social sharing plugin everywhere except posts (using Perfmatters)
Remove Elementor JavaScript
Disabling unused Elementor JavaScript (using Perfmatters)

 

4. Use a lightweight page builder (or none)

Page builders have gotten a bad rep since core web vitals.

Elementor and Divi (specifically) add lots of extra JavaScript to your site. Combine this with Ultimate Add-Ons and other page builders plugins, and your site can quickly become bloated.

I was previously using Elementor and did everything I could to reduce JavaScript. But I was still getting errors in Lighthouse. I decided to redesign my site (again) using Astra + Gutenberg and instantly noticed a big improvement in GTmetrix, PageSpeed Insights, and my overall load times when clicking through my blog. I generally recommend Astra Starter Templates + Gutenberg, GeneratePress, Oxygen Builder, Kadence theme, or Genesis Framework which are lightweight.

Elementor-Souce-Code
Some page builders add extra JavaScript and CSS to your site

There’s a large trend of people replacing slow page builders (click thumbnails to enlarge):

If you don’t want to completely remove your page builder, try hard coding your menu, header, footer, and blog sidebar in CSS instead of relying on a page builder or plugin. CSS is much faster!

 

5. Minify and combine JavaScript files

Minifying JavaScript removes unnecessary characters from the code while combining them merges multiple JavaScript files into one single file (reducing the number of HTTP requests). Combining JavaScript and CSS isn’t always good, so make sure you test your own speed results.

These can usually be done in your cache plugin.

On occasion, minification can break your site. In this case, you’d need to find the problematic files in your source code, then exclude them from JavaScript minification in your cache plugin.

Minify Combine JavaScript Files
Use your cache plugin to optimize JavaScript files

 

6. Reduce JavaScript from third parties

Third-party code can load heavy JavaScript on your site.

Lazy loading advertisements (i.e. AdSense) and establishing earlier connections using preconnect and prefetch can significantly improve your page’s initial load time. Check your third-party code in PageSpeed Insights and try to limit it, or at least optimize it. Social sharing buttons and embedded YouTube videos (and social widgets) are also types of third-party code.

How To Optimize Third-Party Code

  • Maps – only load Maps on contact/local pages.
  • Heatmaps – delay loading heatmap JavaScript in WP Rocket or Flying Scripts.
  • YouTube – lazy load embedded videos and replace iframe with preview image.
  • Fonts – limit fonts, weights, icons, host them locally, and try preloading them.
  • Analytics – host locally and use a smaller tracking code (analytics.js or minimal).
  • Tag Manager – avoid when possible, don’t overtrack, delay loading it’s JavaScript.
  • Advertisements – avoid if possible, reserve space to avoid layout shifts, lazy load.
  • Facebook Pixel – host FB Pixel locally using WP Rocket and delay it’s JavaScript.
  • Social Networks – usually from heavy social sharing plugins or embedded widgets.
  • Gravatars – use a local Avatar plugin to serve local Avatar images and delay them.
Third Party Usage
Third-party code adds even more JavaScript

Prefetching third-party scripts can reduce DNS lookup times. You can do this in WP Rocket, Perfmatters, Pre* Party, and other speed plugins. View which third-party code is loaded on your site, grab their hostnames, and prefetch them. Luke has a list of common domains to prefetch.

Prefetch DNS Requests

 

7. Defer non-essential JavaScript

Social sharing, cookie consents, and other non-essential JavaScript should be deferred if it doesn’t need to load immediately.

If your cache plugin doesn’t already support this, you can try the Async JavaScript plugin. Just grab the JavaScript file that should be deferred and paste it into the Async JavaScript plugin.

 

8. Delay non-critical JavaScript

JavaScript can be delayed until user interaction (scroll, click) using WP Rocket. Or use the Flying Scripts plugin which does the same thing but sets a timeout period in seconds.

I did this with comments (wpdiscuz and Gravatars) so my comments don’t load immediately. Since some of my articles have hundreds of comments, this made my posts load much faster.

In some cases, deferring JavaScript may be enough. But if you have JavaScript that can be delayed, I suggest trying this out.

Delay-JavaScript-Execution
Delay JavaScript using WP Rocket, Perfmatters, or Flying Scripts

 

9. Use a smaller Google Analytics tracking code

Some Google Analytics scripts are larger than others.

Larger scripts collect more data for you to view in Google Analytics, but you may not even be using that data in the first place. If you only need basic data (page views, users, locations, devices, traffic sources, and real-time), you can use the minimal option. If you need more data in Google Analytics, you can use a large script type, but it will also slightly add to your load time.

  • analytics.js – 18.4 KB
  • minimal – 1.5 KB
  • gtag.js v4 – 51.5 KB

Perfmatters, for example, lets you choose your Google Analytics script type and whether you want to disable GA’s Display Features which prevents a second HTTP request to DoubleClick.

Perfmatters Google Analytics Script Type
Use a GA tracking code with a smaller file size (i.e. minimal.js)

 

10. Disable jQuery

Many themes and plugins use jQuery, so be careful when disabling it.

It may be possible to disable certain parts of jQuery (e.g. jquery-migrate) without it breaking your site. Test it in Perfmatters or Asset CleanUp and see if you can at least remove a few KBs.

jQuery-JavaScript
Avoid jQuery-dependent plugins and disable files if they’re not being used

 

11. Disable unused plugin modules

Many plugins are module-based and let you disable individual features you don’t use.

You can do this in JetPack, Ultimate Add-Ons, Rank Math, Yoast, and other module-based plugins. If you’re not using Rank Math’s analysis, disable it. Same concept with other modules.

Rank Math Modules
Module-based plugins let you disable features you don’t use

 

12. Disable Cloudflare email obfuscation

Cloudflare’s email obfuscation loads an extra JavaScript file.

Either you enabled it yourself, or you’re using WP Rocket and checked the “optimal settings” box for Cloudflare. Email obfuscation is supposed to prevent bots from collecting your email, but also loads a JavaScript file throughout your site which will be found in GTmetrix Waterfall.

Cloudflare Email Address Obfuscation
Cloudflare Email Obfuscation adds email-decode.min.js to your site

 

13. Disable WooCommerce scripts on non-eCommerce content

WooCommerce loads extra scripts and styles across your site (even on non-product pages).

The easiest way to disable these is in Perfmatters. Cart fragments update the cart total without refreshing the page, but can sometimes add a few extra seconds to your load time. Choose which options you want to disable and whether speed or cart fragments are more important.

If you’re not using Perfmatters, there are quite a few solutions on GitHub or you can use the Disable WooCommerce Bloat plugin.

Disable WooCommerce Scripts
Use Perfmatters or the Disable WooCommerce Bloat plugin to disable WooCommerce scripts

 

14. Avoid multiple reCAPTCHAs

Captchas also create extra JavaScript files, so limit how many you’re using. If you have a problem getting spam from bots, try putting an image of your email address instead of text.

 

15. Test Cloudflare Rocket Loader

Rocket Loader can be a blessing for speed, but it can sometimes cause issues. Either way, I suggest trying it out. This will defer the loading of all of your JavaScript until after rendering.

If your visitors are local, you may not want to use a CDN at all and choose a host with a data center close to your visitor’s location. Otherwise, CDNs can often do more harm than good.

Cloudflare Rocket Loader
Rocket Loader can hurt or help performance (test carefully)

 

16. Avoid slow plugins with heavy JavaScript

Slow plugins can create lots of JavaScript.

Review this list of slowing loading plugins or use Query Monitor to find your slowest plugins.

Even if some plugins don’t appear in your GTmetrix Waterfall report, that doesn’t mean they’re not slowing down your site. For example, plugins that collect ongoing data (backups, statistics, broken link checker) can slow down your site even though they’re not running on the frontend.

 

Retest Your Website

Run your site though Lighthouse or PageSpeed Insights and check if you still need to remove unused JavaScript. Hopefully you passed or at least trimmed it enough to be a lower number.

Remove unused JavaScript WordPress - Passed

 

Frequently Asked Questions

How do I remove unused JavaScript in WordPress?

Avoid heavy page builders and use an asset unloading plugin such as Perfmatters or Asset Cleanup to disable scripts on pages/posts where they don't need to load. Also try reducing the amount of third-party code loaded on your site.

How do I reduce JavaScript in Divi?

Minify and combine JavaScript files in Divi's Theme Options and consider using Gutenberg instead of Divi blocks since they're more lightweight in terms of JavaScript and CSS.

How do I reduce JavaScript using WP Rocket?

Minify and combine JavaScript files in WP Rocket's file optimization settings and delay third-party JavaScript using the Delay JavaScript Execution option.

Can Autoptimize remove unused JavaScript?

Autoptimize lets you aggregate JavaScript and force it in the head, but this really only helps eliminate render-blocking resources, not remove JavaScript.

How can I remove unused JavaScript from embedded YouTube videos?

Lazy loading videos and iframes, as well as replacing the iframe with a preview image can reduce the amount of JavaScript initially loaded from YouTube. You can also try delaying YouTube JavaScript in plugins like WP Rocket or Flying Scripts.

See Also: My WordPress Speed Guide

Cheers,
Tom

About Tom Dupuis

Tom Dupuis 2017Tom Dupuis writes WordPress speed and SEO tutorials out of his apartment in Denver, Colorado. In his spare time, he plays Rocket League and watches murder documentaries. Read his bio to learn 50 random and disturbing things about him.

Subscribe
Notify of
guest
21 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments