<?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 Dmitry Saprykin on Medium]]></title>
        <description><![CDATA[Stories by Dmitry Saprykin on Medium]]></description>
        <link>https://medium.com/@dimafingy?source=rss-884e5ef4eb24------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*YgT-JhHWNuTw8zjv.</url>
            <title>Stories by Dmitry Saprykin on Medium</title>
            <link>https://medium.com/@dimafingy?source=rss-884e5ef4eb24------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 18:16:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dimafingy/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[Performance tuning for web apps]]></title>
            <link>https://tech.iheart.com/performance-tuning-for-web-apps-bd0b37b887c5?source=rss-884e5ef4eb24------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd0b37b887c5</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[pwa]]></category>
            <category><![CDATA[web-performance]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Dmitry Saprykin]]></dc:creator>
            <pubDate>Wed, 09 May 2018 16:05:55 GMT</pubDate>
            <atom:updated>2018-05-09T16:05:55.589Z</atom:updated>
            <content:encoded><![CDATA[<p>In early 2016 our iheart.com legacy code base was overwhelmingly large, with architectural flaws like a monolithic code bundle, inlining all the app’s css into the initial html, and use of heavy libraries such as moment and cheerio. In the beginning of 2017 we dedicated time for an initiative that we called “Fast Web”, with the goal of improving our end users experience by reducing page load time. By the end of the year we cut “time to interactive” in half with an updated stack, and introduced some PWA (progressive web apps) practices. I will summarize our work in this article and hopefully it will help you fine-tune the performance of your app and avoid some our mistakes we learned along the way.</p><p><strong>1. Low hanging fruit</strong></p><p>It is always a good idea to start with something simple and give your app a quick boost before diving into the heavy duty work.</p><p>The first thing we did was split our bundle in two — entry.js (our JS code) and vendor.js (third-party libraries). The benefit here is the ability to heavily cache vendor.js and not force clients to download it after each release. Eventually we want to achieve full code-splitting, but we still have some refactor work to do before this is possible. Of note, webpack 4 makes this trivial:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/39a707c2cdbc5b00773b3b9c8b5a063d/href">https://medium.com/media/39a707c2cdbc5b00773b3b9c8b5a063d/href</a></iframe><p>Another piece of low hanging fruit was enabling HTTP/2. One of the many advantages of HTTP/2 is reuse of connections and parallel asset downloading over that connection. This removes the overhead of: 3-way handshake, cookies being sent back and forth for each connection between client and server as well as browser limitations on connections per domain. In addition, with HTTP/2 the headers get extra compression which reduces the size of a request. While with HTTP/1.1 it made sense to make as few roundtrips as possible, with HTTP/2, presuming our bundles are all on the same host it is ok to break your scripts into multiple bundles to utilize multiplexing.</p><p>Another cool feature of HTTP2 is server hint/server push. The idea behind server-hint is to use the browser’s idle time to prefetch assets that user will or most likely will need. Simply add the meta tag</p><pre>&lt;link rel=”prefetch” href=”/dist/importantStuff.js”&gt;</pre><p>— and the browser will do the rest.</p><p>Server push pushes assets before the client even asks. That way you can send above the fold css along with html instead of inlining it. However, there is a drawback to this approach — since the server does not know in advance whether or not the client already has pushed resources, this can lead to unnecessary traffic. For that reason we decided not to use it.</p><p>Another interesting performance technique (although you don’t need HTTP2 for it) is DNS warmup. Most of the time our app requests data from more than one domain. It can be assets, media, ads, third-party plugins — in order to reach all these domains the browser needs to resolve their ip addresses through DNS tables. Though not critical, it is still overhead that you can get rid of with</p><pre>&lt;link rel=”dns-prefetch” href=”<a href="http://www.somedomain.com/">http://www.somedomain.com/</a>&quot;&gt;</pre><p>This meta tag tells the browser — you will need this domain address in a future, resolve it now, while you have nothing else to do. Just a small optimization trick that will not take much of your time.</p><p><strong>2. Server rendering (universal app)</strong></p><p>This technique caused a lot of heated debates and was the most tricky and complicated (and as it turns out, least impactful) part of speeding up our app. I will not go into details of how you do universal JS, but I want to give you a breakdown of what I consider pros and cons of this approach.</p><p>Pros:</p><ul><li>Better SEO. The most favorite three letters of all marketing and product people. Server rendering lets crawlers read the content without running JS.</li><li>Arguably a better experience — users see some of the content almost immediately, after the request comes back from the server</li><li>Somewhat faster, especially if data endpoints are close to the rendering server</li></ul><p>Cons:</p><ul><li>Caching can become a headache. Our app sits behind a reverse proxy at our CDN (Fastly) that caches per page, so that consecutive requests to the same page don’t go to origin. If our content changes often (especially in the case of user-specific content), we need to make sure to flush the cache. If on a server we render something that’s personalized to you (say, an avatar) — all the other users will get the same copy of the page. So you need to think hard about what to include in the server render phase. It gets even more interesting when you need to deal with internationalization, when you manage different content per country.</li><li>Potential React diffs; Say there’s a username in a header and we don’t authenticate users on a server so it doesn’t get rendered. On the client we authenticate first (now username is in the store to be rendered) and then kick-off React render cycle. What we’ll end up with is a difference in DOM elements between server and client so React will have to flush the DOM in favor of a newer version throwing a warning. This diminishes the value of server render due to the extra work needed to be done on the client. There’re ways to avoid diffs, but they add up to extra complexity to your app.</li><li>Confusing UX; If your JS bundle isn’t the smallest and it takes time to parse and run, initial html will be unresponsive. User will see elements on the page that would not react to clicking or tapping until the page is ready, and that’s a bad experience.</li></ul><p>My take on universal JS — definitely do some of it. Render meta tags and some of the elements that are not user-specific. However if your app is too big to be parsed and rendered fast enough, it might be a good idea to avoid rendering interactive elements. Also keep in mind, this technique is more about “perceived” loading time than actual. The app’s JS still needs to be downloaded, parsed and run, which to my experience is the biggest problem.</p><p><strong>3. Ship less code</strong></p><p>Smaller javascript bundles make faster page loads. Your “time to interactive” consists of time needed for downloading critical resources, parsing and running javascript until the user is able to use the app. For us, this is the time it takes our player to load and become responsive. Thus, we wanted to make the critical JS as small as possible and defer everything else. This can be done with dead-code elimination aka tree-shaking, code-splitting, and making sure we don’t use heavy libraries when there are slim alternatives (like trading ‘moment’ for date-fns).</p><p>Webpack can help you with all of the above with a little help from our friends:</p><p><a href="https://github.com/jamiebuilds/react-loadable">React-Loadable</a> for component/route split, <a href="https://webpack.js.org/plugins/uglifyjs-webpack-plugin">UglifyJSPlugin</a> for tree-shaking, <a href="https://www.npmjs.com/package/webpack-bundle-analyzer">BundleAnalyzerPlugin</a> to analyze the optimization results.</p><p>Let’s start with tree shaking. If you’re not familiar with the concept, here’s a brief explanation. Let’s say you require a big library like <a href="https://lodash.com/">Lodash</a> but you only use 5% of it’s methods. Unused, or dead code will still be shipped in the bundle unless we do what’s called tree shaking, which removes all of the library’s code that you aren’t using anyway.</p><p>To understand tree shaking, we need to touch a bit on static vs dynamic imports. Dynamic imports use the require method; with it, you can import your code based on a condition. However, it’s impossible to tell in advance whether or not this code is actually being used. To address this, use the import directive, which guarantees that imported stuff will be loaded.</p><p>So first, we use “import’’, but in order for it to work we need to use named imports.</p><pre>Avoid things like:</pre><pre>import * from ‘lodash’;</pre><pre>or</pre><pre>import lodash from ‘lodash’;<br></pre><pre>Use:</pre><pre>import { debounce } from lodash</pre><p>Funny thing about lodash though is that you still need an additional babel plugin called <a href="https://github.com/lodash/babel-plugin-lodash">babel-plugin-lodash</a> to make this library shakeable.</p><p>After making sure that all the code is now being imported statically (webpack will mark unused code with specific comments), apply <a href="https://webpack.js.org/plugins/uglifyjs-webpack-plugin">UglifyJSPlugin</a> to webpack config:</p><pre>plugins: [<br> new UglifyJsPlugin()<br>]</pre><pre>In webpack4 it is even easier: </pre><pre>{  <br>   mode: production <br>}</pre><p>Now, our bundle will only have the code that is in use. Exactly what we wanted.</p><p>The next important thing to do is code-split. The idea here is to create multiple smaller bundles and request them asynchronously when needed. The easiest path would be to split by route, so we end up with bundles like home.js, about.js etc. The downside of this approach is that we either ship repetitive code in those bundles (shared dependencies) or we put all the shared code in entry.js and force clients to download a lot of unused code on initial request. Arguably the better approach would be to split by components. I don’t advocate a 100% split, but my rule of thumb is to split all the views, big components, components with heavy dependencies and components used in more than two spots.</p><p>If you use React for your view layer, the <a href="https://github.com/thejameskyle/react-loadable">react-loadable library</a> would be a great choice. It also has very good documentation. Unfortunately as of now it doesn’t let you create an abstraction so that you always need to import react-loadable in each place you code-split, but it is still worth using.</p><p>After you’ve done splitting and shaking, apply <a href="https://www.npmjs.com/package/webpack-bundle-analyzer">BundleAnalyzerPlugin</a> to webpack config which will open a new browser tab after each build with the results of splitting. Make sure that split bundles don’t share the same code.</p><p><strong>4. Code-split css and ship only above the fold styles on initial request</strong></p><p>Another constant topic of heated debates is handling css. This is something that needs to be taken with great care. Top choices of the past — sass and less. Not that long ago, they were overshadowed by css-in-js (styled-components, glam, glamorous, emotion). It is hard to make a definite distinction between each approach but in essence, less and sass use their own engines to parse and transpile css, while the latter use plain JS to do the job. Beyond the engine, there is also a philosophical difference — the use of global stylesheets vs styled, isolated components. The core idea is this: Instead of creating classes of different specificity — from generic ‘.container’ to very specific ‘.blue’, ‘.alignLeft’ etc we think of styles that belong to one and only one component. As a result we don’t pollute global namespace and styles can’t get overwritten by accident, when then login button all of a sudden changes its shape after you restyled your news page footer.</p><p>At iHeart we’ve chosen Emotion JS to do the job, for several reasons — efficiency (<a href="https://medium.com/@tkh44/emotion-8-9f892346d0af">check out run-time speed comparisons and latest features</a>), composability, theming and easy tree shaking and code-splitting (something that wasn’t trivial in the past). Emotion comes with a solution for server-rendering as well — inlining above the fold css into the initial html. Under the hood, Emotion works pretty much like any other css-in-js library — uses styleElement.sheet.insertRule method (supported in all browsers and IE9+) to inline new styles on a fly, once the corresponding component gets rendered.</p><p>An example of a style with Emotion:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b2d256158811719974913e4331af955f/href">https://medium.com/media/b2d256158811719974913e4331af955f/href</a></iframe><p>Vs. the old way:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/77b18f5736e577c99e5800c2e827d5de/href">https://medium.com/media/77b18f5736e577c99e5800c2e827d5de/href</a></iframe><p>Before we started using Emotion, our initial HTML was 240Kb including minified inline CSS. After we switched to Emotion we cut initial HTML size by 35%, resulting in a full second page load time reduction. In addition, our styles became more predictable and easier to maintain / debug. (There is a story best told over a beer regarding a logo fix that resulted in an authentication workflow failure).</p><p><strong>5. Use Service Workers for caching</strong></p><p>PWA is a trend of 2018 and for a good reason. It is a big step towards native feel in web apps, with significant load time reduction and an offline experience. PWA stands for “progressive web apps” and was introduced by Google. Under the PWA umbrella sit many optimizations, and mobile-friendly/reliability focused techniques: serving pages over HTTPS, responsive design, offline support, code-split, service workers and many more. You can check if your app is PWA compliant using the Lighthouse tool (<a href="https://chrome.google.com/webstore/detail/lighthouse/blipmdconlkpinefehnmjammfjpmpbjk?hl=en">Chrome extension</a>). Here I’ll be covering a service worker use.</p><p>A service worker is a script that the browser runs in a separate thread that maintains your app’s cache, does push notifications and background sync, adds a loading screen for android devices and more. I recommend google’s <a href="https://github.com/GoogleChrome/workbox">workbox plugin</a>. It works with webpack and takes little to no time to set up. The one important requirement is — your app needs to run on HTTPS in order to use service workers. After <strong>npm i workbox</strong> all you need to do is apply a <a href="https://www.npmjs.com/package/workbox-webpack-plugin">webpack plugin</a> and create the manifest:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f187d1dda3997f61f2e68265db272ad/href">https://medium.com/media/2f187d1dda3997f61f2e68265db272ad/href</a></iframe><p>Nothing too fancy — we cache our assets generated by webpack, jpg/png, and all the images coming from our image scaler. In the future we’re planning on adding offline experience and cache ahead to preload async routes, and most used code-split components.</p><p><strong>Conclusion</strong>.</p><p>Optimizing performance of a large app is not a trivial task. Many times removing a bottleneck requires a major refactoring of poorly designed layers of code. So even when performance is not a concern, always ask yourself before implementing a feature, how will it perform? How much will this new library add to the code size? Does it need to go to the main bundle or can it be split and loaded after?</p><p>I recommend the following approaches for performance optimizations:</p><ol><li>Measure each iteration so that you can see whether the implemented techniques work and you’re going in theright direction. We use a combination of <a href="https://www.webpagetest.org/">Webpagetest</a>, <a href="https://developers.google.com/web/tools/lighthouse/">Lighthouse</a> and good-old profiling in Chrome dev tools.</li><li>Start with low hanging fruit: upgrade to HTTP/2, add DNS pre-fetch, server-hint and service workers. These will not require a major refactor but will help gain some momentum.</li><li>Always profile. Some big gains can be found hiding in surprising places like third-party iframes that hang and don’t allow window.onload to fire, or poorly designed components that force the DOM to repaint 10 times on initial load (I’ve seen worse)</li><li>When code-splitting, consider component split rather than route split to avoid redundancy; always keep caching in mind — split components can be cached for longer time than the whole route.</li><li>Use an image scaling api to serve images per viewport size (avoid png where possible, the format doesn’t compress photos well).</li><li>Inline only above the fold css.</li></ol><p>And finally — before introducing a new fancy library to your code, think of two reasons why you don’t need it. If you can think of those — don’t introduce it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd0b37b887c5" width="1" height="1" alt=""><hr><p><a href="https://tech.iheart.com/performance-tuning-for-web-apps-bd0b37b887c5">Performance tuning for web apps</a> was originally published in <a href="https://tech.iheart.com/">iHeartRadio Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>