DEV Community

Antonio Erdeljac
Antonio Erdeljac

Posted on

Simple JS thread optimization using Partytown (Web Workers)

Javascript Thread

Javascript is a single-threaded language which means it has only one call stack that is used to execute the program.

In simpler terms, this means that only one line of code can be executed at a time.

While you most likely won't notice this as an issue whilst developing simpler apps, once you start adding 3rd party libraries such as Google Analytics, Intercom or other heavy packages that are not required to be in the critical path you will probably notice the main thread starting to clog up.

This will cause your app to slow down, which leads to bad user experience, and higher churn rate.

Web workers

As per MDN definition, web workers are means for web content to run scripts in the background threads, thus offloading the main call stack.

They are capable of performing tasks without interfering with the use interface, and can perform I/O using XMLHttpRequest.

Read more about web workers here

Partytown

Partytown is a lazy-loaded library created to help relocate resource intensive scripts into a web worker, thus unclogging the main thread.

It's philosophy is that main thread should be dedicated to your code, and scripts which are not required to be in the critical path should be moved to a web worker.

Image description

Integration

Following Partytown's simple React integration, we can see how easy it is to offload the main thread.

Visit the full documentation here.

Install

Image description

Configure

Image description

Partytown Script

Image description

Copy Library Files

Image description

Thanks for reading!

Connect with me on Linkedin.

Top comments (4)

Collapse
 
ilucin profile image
Ivan Lučin

@antonioerdeljac cool article, I might try web workers to offload some background processing in Productive. One major comment though - you can't say JS is single threaded without mentioning event loop and how async code execution works ;)

Collapse
 
antonioerdeljac profile image
Antonio Erdeljac

Thanks so much for the feedback!

I absolutely agree with you, will update the article with deeper explanation.

Collapse
 
hiepxanh profile image
hiepxanh

can you provide example repo? I'm having 404 error

Collapse
 
hamzaalvi profile image
Hamza Alvi

@antonioerdeljac I'm having 404 error can you provide the repo