First, what is Partytown? It's a JS library that lets you offload 3rd party scripts to a web worker to remove the negative performance impact they can have on your site
How do you integrate Partytown? You can easily add it to any site with a small snippet, and then tag any scripts that you want to load in the Web Worker with type="text/partytown" partytown.builder.io/html
Any scripts that you add type="text/partytown" will load by default in a Web Worker, but have full access to global variables
We use JS Proxies to supply main thread globals to the worker thread, by intercepting them and forwarding to the main thread
And here is the magic part: we use a *synchronous* xhr request to block the worker thread to retrieve the needed value from the main thread
And now we can use a Service Worker to intercept the /proxytown request, and async postMessage to the main thread to get the needed value, and return it
And that's it! The end result: you can now seamlessly drop in a whole range of third party scripts to run in a web worker, removing the main thread perf cost of them
Bonus - if you are wondering how Partytown handles objects or functions as return values, we can’t send the actual ref back, send back a proxy object pointing to it. When methods are accessed or called, we invoke them on the original and send the value back
Bonus pt 2: a better look at what happens in each thread
Optimizing your largest contentful paint (LCP) can be hard
Here are 8 tips, with code snippets and visuals, to help your pages load fast for optimal SEO and UX
🧵👇
First, how is LCP measured?
> The Largest Contentful Paint (LCP) metric reports the render time of the largest image or text block visible within the viewport, relative to when the page first started loading
As much as possible, serve all pages and content pregenerated from a CDN cache. This ensures that response times are fast, and content can be visible as quickly as possible
In short, JS VMs try to assume a shape of an object using a hidden class. When the shape changes, this can lead to a deopt
It's the same reason why setting a property to null/undefined can be faster than deleting:
A Map, on the other hand, is optimized for this very use case of frequently adding and removing keys (see the "performance" table row here): developer.mozilla.org/en-US/docs/Web…
Well, you are in luck. Image components provided @cloudinary, @nextjs, @GatsbyJS, and @nuxt_js do many of these optimizations (like nextgen format, dynamic srcset, etc) for you completely automatically!
If you are wondering "between scripts, images, and iframes, which would have the most impact on my site speed to put time into optimizing" - I got you: builder.io/c/performance-…