'How to load 3rd-party scripts into a site using web workers
I have seen a lot about offloading large scripts from the main thread to help improve website performance and Google's Core Web Vitals. I am curious if there is a way to use web workers to load a third-party script, like Google Analytics or the Facebook pixel (or really any third party script), so that these processes don't bog down the main thread.
If it is possible, could this also be done, in theory, for external CSS stylesheets or CSS libraries?
Solution 1:[1]
I am curious if there is a way to use web workers to load a third-party script, like Google Analytics or the Facebook pixel (or really any third party script), so that these processes don't bog down the main thread.
No. Those scripts are designed to interact with the DOM (which isn't available inside a worker). They aren't CPU intensive anyway so you wouldn't see any performance benefits.
If it is possible, could this also be done, in theory, for external CSS stylesheets or CSS libraries?
No. Workers run JS not CSS (and again, CSS interacts with the DOM).
Solution 2:[2]
Since this answer appears on the first page when googling on how to offload 3rd party scripts to Web Worker I thought it would be nice to update:
There is a library called Partytown which does exactly this and much more
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Quentin |
Solution 2 | Samuel Petroline |