Third-party scripts are both a blessing and a curse. They power analytics, personalization, ads, chat widgets, A/B testing, and countless other features that are hard to build from scratch. But they also come at a cost: slowing down your site, blocking rendering, and making users wait.
The challenge is simple: you want the benefits of these integrations without letting them ruin performance. One modern approach is to offload scripts into web workers, giving them their own space to run without choking your main thread.
But before we jump into workers, let’s walk through the broader toolkit you have for optimizing third-party loading.
Why Third-Party Scripts Can Be Painful
Every JavaScript file that runs on your site adds work for the browser. If it’s large or synchronous, it blocks the main thread: the single-threaded engine responsible for painting, animating, and responding to user input.
When you add multiple scripts (especially third-party ones you don’t fully control), you risk:
- Render-blocking: A script may hold up the page from loading until it’s finished downloading and executing.
- Execution jank: Heavy computation eats up CPU cycles, delaying user interactions.
- Network delays: Third-parties live on other domains, so DNS lookups and TLS/SSL server connections introduce latency.
- Maintenance risk: If the provider’s script is slow, outdated, or buggy, your performance suffers.
That’s why following best practices around script loading is essential.
Best Practices for Loading Third-Party Scripts
Third-Party Scripts can have negative impact on performance of your website so loading them efficiently is crucial for well performing websites. Let’s take a look at the few most important practices:
- Use
async
anddefer
: load scripts asynchronously to avoid blocking the main thread - Use Resource Hints (
dns-prefetch
andpreconnect
): prepare connections to third party domains in advance - Lazy-load below-the-fold script: if a widget isn’t visible until a user scrolls (like a chat bubble or a video embed), don’t load it upfront
- Self-host when possible: instead of relying on a third-party CDN, serve critical scripts from your own domain to avoid extra DNS lookups and connection handshakes
Check out our detailed third-party optimization guide to learn more about reducing the performance impact of third-party code.
Web Workers: Moving Work Off the Main Thread
JavaScript on the web runs inside a single-threaded environment by default. This thread — the main thread — has a lot of responsibilities: rendering the page, handling user interactions, painting animations, and running your app’s JavaScript.
If we add third party scripts here, where many of them are non-essential for the very first interaction (ads, analytics, social widgets), but they often compete with your app for the main thread. That’s why sites that rely heavily on third-parties often struggle to pass Core Web Vitals like Interaction to Next Paint (INP).
This is where web workers become a powerful tool.
A web worker is a way to run JavaScript in a background thread, separate from the main thread. As a result, the main thread is less busy and rendering and handling user input can happen faster.
Workers don’t have access to the DOM (which stores the page content) directly. But they can handle expensive tasks like computation, parsing, and third-party execution without blocking rendering.
Think of it as hiring an assistant: the main thread handles the "front desk" (user input, UI updates), while the worker takes care of the "back office" (heavy lifting).
Let’s take a look at the following simple example of a worker. The worker.js
file contains a heavy computation that we want to offload to a worker:
// worker.js
self.onmessage = function (e) {
const result = expensiveCalculation(e.data);
self.postMessage(result);
};
function expensiveCalculation(input) {
let total = 0;
for (let i = 0; i < 1e8; i++) {
total += Math.sqrt(i * input);
}
return total;
}
And then, in our main.js
we can initialize a new worker and trigger the heavy computation:
const worker = new Worker("worker.js");
worker.postMessage(42); // send data to worker
worker.onmessage = function (e) {
console.log("Worker result:", e.data);
};
This way, we can offload the heavy computation from the main thread to improve performance.
Using Partytown to optimize third-party performance
Partytown is a clever library that offloads third-party scripts into web workers automatically. As a result, the main thread can focus on rendering page content and handling user interactions.
It proxies calls back to the DOM when needed, so third-party code can still modify page content.
Let’s take a look at the following basic example of how Partytown is implemented in code:
<!-- Load Partytown (place in <head>) -->
<script src="partytown/partytown.js"></script>
<!-- Configure your third-party inside Partytown -->
<script type="text/partytown" src="https://example.com/tracking.js"></script>
The magic here is the type="text/partytown"
— instead of running on the main thread, Partytown intercepts it and executes inside a worker.
Kellen Mace created a great comparison of how the performance of Next.js application changes when adding Google Tag Manager the traditional way and then by using PartyTown.
In his article, he audited his website before the change which resulted in a Lighthouse Performance score of around 70 out of 100, and few recommendations like Minimize main-thread work
and Reduce the impact of third-party code
. After he added Partytown to this application, the Lighthouse score increased to around 99 out of 100 and both recommendations were no longer shown.
Comparing the Sources tab in the devtools shows that indeed the slow scripts and Google Tag Manager was moved from the main thread which resulted in better performance.
A practical workflow for third-party optimization
The best way to optimize third-party scripts is to layer improvements gradually. Start with the basics: add async
or defer
to scripts and use resource hints like dns-prefetch
or preconnect
to cut down on network delays. These small tweaks prevent obvious render-blocking.
Next, delay anything non-essential. Widgets that only appear below the fold—such as chat bubbles or video embeds—can be lazy loaded so they don’t slow down the initial page load. When possible, self-host important scripts to reduce DNS lookups and gain more control over caching.
If performance is still impacted, consider using Partytown to move third-party execution into a Web Worker. This keeps the main thread focused on rendering and interaction, while still allowing external scripts to run.
By layering these strategies—simple loading attributes, lazy loading, self-hosting, and finally workers—you can keep your site fast while still benefiting from third-party services.
Audit a website for third-party scripts with DebugBear
Let's audit www.armani.com to see how third-party scripts impact website performance.
Let’s now audit this website in with the free DebugBear website speed test. I have already run a test that you can check out here. Let’s take a look at the recommendations by first.
We can clearly see that DebugBear already discovered opportunities to improve in terms of third party script handling.
Furthermore, we can go to the requests tab where we can see the waterfall of requests and if we filter to view just JavaScript files we can see list of scripts that will be used in this page. Many of them that are loaded from third parties. For some we can see warnings to inform us that we can optimize the script.
What could also be useful is seeing how metrics such as Core Web Vitals are affected by these scripts. We can go to the web vitals tab to see Interaction to Next Paint as well as the CPU processing time for each resource.
This gives us information about how the scripts area loaded and how much CPU time they need to be properly loaded.
Summary: speed up third-party code with Partytown and other optimizations
Third-party scripts aren’t going away anytime soon. Over time, as your site becomes richer and more complex, it’s easy for little inefficiencies to creep in. Scripts can overlap, old code can pile up, and performance can take a hit. Running reports or scheduling regular check-ups is a smart way to spot those trouble areas early and clean things up before they slow users down.
Of course, not everything is in your hands: third-party code with well-known issues can still drag down performance. But with careful loading strategies and new tools like Partytown, you can reduce their impact dramatically.
See the impact of your changes with continuous page speed monitoring
If you're trying to optimize your website performance, check out DebugBear for continuous web performance monitoring and analysis:
- Identify slow pages
- See what technical issues are slowing you down
- Get alerted when there's a performance regression
For example, DebugBear's script analysis for the Largest Contentful Paint and Interaction to Next Paint metrics can help you see whether third-party scripts are slowing you down or if the issue is with your won code.


Monitor Page Speed & Core Web Vitals
DebugBear monitoring includes:
- In-depth Page Speed Reports
- Automated Recommendations
- Real User Analytics Data