<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Vedansh Garg on Medium]]></title>
        <description><![CDATA[Stories by Vedansh Garg on Medium]]></description>
        <link>https://medium.com/@vedansh.garg.7?source=rss-934279b2e3e7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*IFqcDjXCpNdeYINR6qaO1A.png</url>
            <title>Stories by Vedansh Garg on Medium</title>
            <link>https://medium.com/@vedansh.garg.7?source=rss-934279b2e3e7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 20:55:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vedansh.garg.7/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Improving performance of Web apps using Web Workers]]></title>
            <link>https://medium.com/@vedansh.garg.7/improving-performance-of-web-apps-using-web-workers-d69ae011126e?source=rss-934279b2e3e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/d69ae011126e</guid>
            <category><![CDATA[webworker]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Vedansh Garg]]></dc:creator>
            <pubDate>Mon, 22 Jun 2020 07:02:01 GMT</pubDate>
            <atom:updated>2020-06-30T15:50:31.518Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o9lhcDA5mIptlIySVjRlBA.jpeg" /></figure><p>For a language upon which the whole front-end world is set, it came as a surprise to me that <strong>Javascript is single-threaded</strong>. That&#39;s right! Every single tab of your browser is run by Javascript running on a single thread. That includes all the rendering, ajax requests, event listeners, setIntervals, heck even the console. The CPU time of that single thread is divided between all these to provide us a seamless experience, so-much-so that we even forget this limitation.</p><p>Javascript runs fine on a single thread. But if it gets stuck in any CPU intensive task, its ability to render and manipulate DOM gets hampered. Now, this is very rare, because on most occasions, the UI receives the data from the backend in a form that is ready to display. But sometimes, the requirement calls for your web-app to process some data (sorting, computation, etc.). If this data is big, it can lead to a laggy or even an unresponsive UI as the main thread is busy computing.</p><figure><img alt="Chrome Tab Unresponsive" src="https://cdn-images-1.medium.com/max/417/1*iO9s-4YCLuT9KWNpxOoYYQ.jpeg" /><figcaption>Ring any bells?</figcaption></figure><p>This is where <strong>Web Workers</strong> come in. Web workers allow us to run our own scripts in the background on a different thread. Now, it&#39;s not as magical as it sounds, as background scripts don&#39;t have access to DOM, or any imported components or libraries. But it will solve our problem very well:</p><ul><li>The main script running in the foreground handling all the DOM manipulation.</li><li>A background worker script handling all the heavy processing.</li></ul><p>For running some code in web workers, it must be provided as a <strong>separate JS file</strong>. This is because our main-script and web-worker script must be completely independent so that they can run on separate threads. But then, how will they communicate? The window.postMessage() method safely enables cross-origin communication. Thus, the two scripts will communicate by sending(<em>posting</em>) and receiving(<em>listening)</em> messages.</p><h3>Enough theory, Lets code!</h3><p>I have a basic stop-watch react app which I think will be perfect for this demonstration. You can find the complete code at <a href="https://github.com/vedanshgarg/stop-watch"><strong>Github</strong></a>. The demo is live <a href="https://vedanshgarg.github.io/stop-watch/"><strong>here</strong></a>.</p><p>Let’s start by creating the script that’ll run in the background. The heavy computation task we are gonna do is nested <em>for</em> loops incrementing a value. We’ll add an event listener to listen to messages from the main-script and send the result back using <em>postMessage</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/06fe27eccae5d07d73cccaf34da9fade/href">https://medium.com/media/06fe27eccae5d07d73cccaf34da9fade/href</a></iframe><p>I have just passed a single value here “<em>score</em>”. You can pass arrays, objects, etc. as well.</p><blockquote>Note: postMessage always sends a copy of your data. Thus, there will be a noticible performance drop if the message size is &gt;100MB.</blockquote><p>But wait, we have to provide <em>incrementWorker.js</em> as a separate file. This will require excluding it from our existing build workflow and converting it to ES5 and then referencing its URL to create our Worker … and many more hassles. Any workarounds? Yes! Its called <strong>Blob</strong>.</p><p>Blobs allow us to create temporary files whose URL can referenced using URL.createObjectURL(). Its constructor takes an array of values. Even if we have just one string to put in the blob, we must wrap it in an array.</p><p>Let&#39;s create a WebWorker class that does all this for us and returns a nice worker for us to use.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bf971f8a1b163859af98dd4056c15b99/href">https://medium.com/media/bf971f8a1b163859af98dd4056c15b99/href</a></iframe><p>We enclosed our code in (...)() so that the script is executed as soon as it&#39;s mounted. Thus our web-worker script starts listening to messages right away!</p><p>Now, all we need to do is create a WebWorker object with the <em>incrementWorker.js script</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32b9e95c0553e4121f5553647b28cc0e/href">https://medium.com/media/32b9e95c0553e4121f5553647b28cc0e/href</a></iframe><p>Remember, we still need to post messages &amp; add a listener to receive messages from <em>incrementWorker.js </em>in our main code<em>. </em>Let’s do that now.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3e57f766269d30867ecbbce3d757828a/href">https://medium.com/media/3e57f766269d30867ecbbce3d757828a/href</a></iframe><p>When the <em>incrementWithWorker</em> function is called, we post a message to the <em>incrementWorker.js</em> script by</p><pre>worker.postMessage(score);</pre><p>The worker processes and messages us back the result which we listen via the eventListener we added in the <em>useEffect</em> upon initial mount.</p><blockquote>Lets checkout the <a href="https://vedanshgarg.github.io/stop-watch/">Demo</a> now.</blockquote><p>First, we’ll test out what happens when we try to compute using the Main thread. Start the stop-watch and click <strong>“Add using Main thread”</strong></p><p>The following observations are made:</p><ul><li>The stop-watch stops for a few moments.</li><li>The console has incrementing numbers every 500ms. That stops for a while.</li><li>As per the code, while calculating the score, <em>loading=true,</em> so buttons should be disabled and the score must be greyed out. But that does not happen.</li></ul><p>The reason is that the main thread is busy running the nested for loops, so it is unable to handle the tasks its meant to do.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iChjSKTsrqkkW6CaRzyfiw.png" /></figure><p>Let&#39;s try now using our worker script. Click <strong>“Add using WebWorker thread”</strong>.</p><p>It works just as expected. None of the 3 points mentioned above are noticed here. <strong>Hurrah!!!</strong></p><blockquote>You can never create your web-app completely multithreaded. But with Web Workers, it&#39;s possible to transfer the CPU intensive work to 1 or even more background scripts. This will ensure your main script is always ready to respond to the user providing a lag-free snappy experience. And that’s the end-goal in front-end development, isn’t it?</blockquote><p>Thank You for reading this far. Do leave a clap if it was worth your time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d69ae011126e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>