How Partytown's Sync Communication Works
Partytown relies on Web Workers, Service Workers, JavaScript Proxies, and a communication layer between them all.
- Scripts are disabled from running on the main thread by using the
type="text/partytown"
attribute on the<script/>
tag. - Service worker creates an
onfetch
handler to intercept specific requests. - Web worker is given the scripts to execute within the worker thread.
- Web worker creates JavaScript Proxies to replicate and forward calls to the main thread APIs (such as DOM operations).
- Any call to the JS proxy uses synchronous XHR requests.
- Service worker intercepts requests, then is able to asynchronously communicate with the main thread.
- When the service worker receives the results from the main thread, it responds to the web worker's request.
- From the point of view of code executing on the web worker, everything was synchronous, and each call to the document was blocking.