Written by:
Ben Haig
August 16, 2023 at 6:44 PM
Byte-Sized Development Insights
Partytown is an intriguing solution designed to help developers streamline third-party scripts on web pages. Its primary mission? To push these scripts off the main browser thread and into a web worker. By doing so, the overall performance and user experience of the web pages improve. The primary focus is on third-party scripts like analytics, which can often bog down site performance.
Conventionally, the communication between the main thread and worker thread has always been asynchronous. Partytown has effectively changed this dynamic, allowing the web worker to access the DOM synchronously.
In a typical script without asynchronous cues like async/await, promises, or callbacks, the call is blocking. Partytown uses a combination of Web Workers, Service Workers, JavaScript Proxies, and an intricate communication layer to ensure third-party scripts work just as they were initially coded.
Not all scripts are automatically shifted to the web worker. Developers choose which scripts should utilize Partytown by adding the attribute type="text/partytown" to the <script> tags. This prevents the main thread from executing the script and lets Partytown query the script.
Serialization is vital for data to transition between threads. Partytown automates the process of serializing and deserializing data shared across threads.
Developers might notice numerous proxytown requests in the network tab. These requests are intercepted by the service worker and managed by Partytown locally, not affecting performance.
DOM operations are deliberately throttled within the worker. Partytown groups many operations to minimize the calls between threads.
Partytown might not be the best fit for UI-intensive scripts but is ideal for scripts like Google Tag Manager or Facebook Pixel.
Partytown can't access or set the origin’s document.cookie, localStorage, or sessionStorage in cross-origin iframes.
Some scripts employ a setInterval() loop that continuously scans the document, which can overwhelm Partytown.
Partytown offers a means to enhance web performance by offloading third-party scripts to web workers. By understanding its workings and trade-offs, developers can harness its power where it fits best.