<?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 Naman Saini on Medium]]></title>
        <description><![CDATA[Stories by Naman Saini on Medium]]></description>
        <link>https://medium.com/@saininaman98?source=rss-5706633ede31------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*0uKC85Hno0Ik0y4QOwc0Qg.jpeg</url>
            <title>Stories by Naman Saini on Medium</title>
            <link>https://medium.com/@saininaman98?source=rss-5706633ede31------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 18:05:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@saininaman98/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[Module Federation Pipeline — Part 1]]></title>
            <link>https://medium.com/engineering-housing/module-federation-pipeline-part-1-6c81ea15fe16?source=rss-5706633ede31------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c81ea15fe16</guid>
            <dc:creator><![CDATA[Naman Saini]]></dc:creator>
            <pubDate>Wed, 07 Jun 2023 07:39:02 GMT</pubDate>
            <atom:updated>2023-06-07T07:39:02.256Z</atom:updated>
            <content:encoded><![CDATA[<h3>Module Federation Pipeline — Part 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gUjlJp2K2jWSYOpAHy3qYQ.png" /></figure><h4>What is Module Federation?</h4><p>Module Federation is a feature in modern JavaScript module bundlers like Webpack that allows separate applications or micro-frontends to share code and resources seamlessly. It enables the development of modular and independent components that can be distributed across different applications, allowing for greater flexibility, code reuse, and improved performance.</p><p>With Module Federation, applications can dynamically load and consume modules from other applications, eliminating the need to bundle everything into a single monolithic application. This approach promotes a more scalable and maintainable architecture, as changes or updates to individual modules can be deployed independently without affecting the entire system.</p><h4>Current architecture of Housing</h4><p>In our current architecture, we utilize module federation exclusively on the client side. This means that any page or route we want to fetch from our server should not be a federated module, but rather a part of the host app that hosts that specific route.</p><p>For instance, when opening the homepage of housing.com at <a href="https://housing.com/">https://housing.com/</a>, it is considered a part of our demand application. In this scenario, the demand application is responsible for fetching the container files of all other applications within our micro-frontend setup. This process allows us to obtain different modules from sources other than the demand application.</p><p>You can observe this in action in the screenshot below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vxzRqfR7rLyyiLcsBadalw.png" /><figcaption>Other containers being fetched on homepage apart from demand</figcaption></figure><p>The container file mentioned above is generated during the build step of Webpack. However, in order for this functionality to work, we need to add a specific plugin and configure it accordingly.</p><p>To achieve this, we include a plugin called ModuleFederationPlugin in our Webpack configuration. This plugin plays a crucial role in enabling module federation. By adding the plugin and specifying its configuration, we can ensure that our applications can share code and resources seamlessly.</p><h4>Implementation steps:</h4><ol><li>In order to enable module federation, we need to add the <a href="https://webpack.js.org/plugins/module-federation-plugin/">ModuleFederationPlugin</a> to the Webpack configuration of each application in our setup. It’s important to note that this configuration is specific to the client build of our application and does not apply to the server side. The reason for this is that the ModuleFederationPlugin is designed to support client-side federation only.</li><li>This plugin requires some configuration, and there are various options available based on our needs. Here are a few important ones. Please refer to the sample configuration code at the end.</li></ol><p><strong>i. ‘name’:</strong> Specifies a unique name for the container (host) project. This name will serve as the key to add this specific container to the window object.</p><p><strong>ii. ‘filename’:</strong> Acts as the filename for the container. When we provide a URL to fetch this container from another app, it will end with …${filename}.js.</p><p><strong>iii. ‘exposes’:</strong> An object that specifies the modules exposed by the current project, making them accessible for remote projects. For example, in the code snippet below, this container exposes a module located at the path “./routes/demandRoutes” with the name “exposedRoutes”.</p><p><strong>iv: ‘remotes’:</strong> Defines the remote modules consumed by the current project. It allows us to specify the remote entry points and the exposed modules. This is used for static remotes when we want to fetch remote modules statically. For instance, in the code snippet below, whenever Webpack encounters ‘supply’ in an import path, it fetches the supplyContainer from the URL mentioned in the ‘remotes’ key and extracts the respective module from this container.</p><p><strong>v: ‘shared’:</strong> Specifies the shared modules and their versions (using the ‘requiredVersion’ key). Shared modules are loaded only once, even if multiple projects depend on them. There is also a ‘singleton’ key that, when set to true, indicates that only a single instance of this shared module will be created among different apps. Otherwise, multiple instances would be created for each federated app, but the code of this module would only be loaded once. For example, in the code snippet below, the ‘react’ version 18.2.0 is set to be a singleton.</p><pre>const { ModuleFederationPlugin } = require(&#39;webpack&#39;).container;<br>module.exports = {<br>  plugins: [<br>    new ModuleFederationPlugin({<br>      name: &#39;demand&#39;,<br>      filename: `demndContainer.m.m.js`,<br>      exposes: {<br>        exposedRoutes: &quot;./routes/demandRoutes&quot;<br>      },<br>      remotes: {<br>        supply: &#39;supply@https://supply-app.com/supplyContainer.js&#39;,<br>        inventory: &#39;inventory@https://inventory-app.com/inventoryContainer.js&#39;,<br>      }<br>      shared: {<br>        react: {<br>          singleton: true,<br>          requiredVersion: &#39;18.2.0&#39;<br>        },<br>        &#39;react-redux&#39;: {<br>          singleton: true,<br>          requiredVersion: &#39;8.0.2&#39;<br>        },<br>    }),<br>  ],<br>};</pre><p>3. If we have specified the ‘remotes’ configuration in our ModuleFederationPlugin, there is no need for any additional steps. Webpack will automatically fetch the container and its respective module when it encounters an import statement that matches our remotes.</p><p>However, if we haven’t specified ‘remotes’, it indicates that we want to dynamically fetch containers and their exposed modules. There are multiple ways to fetch an app’s container (let’s say the ‘demand’ app) based on our specific use case. In our case, we achieve this by creating a script tag with its ‘src’ attribute set to the path of the demand’s container file. As mentioned earlier, this path ends with …${filename}.js, which is defined in the demand&#39;s ModuleFederation plugin configuration. When the script tag is executed, the container is added to the window object and can be accessed using the value specified in the &#39;name&#39; field of the demand&#39;s module federation plugin configuration.</p><p>4. Now, we can access the container file to obtain the required module. Each container exposes methods such as ‘<strong>init</strong>’ and ‘<strong>get</strong>’. To access a module from the container, we need to first initialize the container within the specified scope using the ‘init’ function. Only after initialization, we can asynchronously load the module from the container using the ‘get’ function. For a comprehensive understanding of how this process works, please refer to the following link: <a href="https://webpack.js.org/concepts/module-federation/#dynamic-remote-containers">Webpack Module Federation — Dynamic Remote Containers</a>. Take a look at the sample code snippet, which does the same.</p><pre>const loadComponent = async (app, module) =&gt; {<br>  // Initializes the share scope. This fills it with known provided modules from this build and all remotes<br>  await __webpack_init_sharing__(&#39;default&#39;)<br><br>  const container = window[app] // or get the container somewhere else<br>  // Initialize the container, it may provide shared modules<br>  await container.init(__webpack_share_scopes__.default)<br>  const factory = await window[scope].get(module)<br>  const Module = factory()<br>  return Module<br>}</pre><p>The module returned by this function includes a ‘default’ property that holds the actual module code, which can be accessed and utilized.</p><p>This concludes the current article. In the next part, I will discuss how we successfully implemented module federation for our server-side application and integrated it into our architecture.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c81ea15fe16" width="1" height="1" alt=""><hr><p><a href="https://medium.com/engineering-housing/module-federation-pipeline-part-1-6c81ea15fe16">Module Federation Pipeline — Part 1</a> was originally published in <a href="https://medium.com/engineering-housing">Engineering @ Housing/Proptiger/Makaan</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CSS Pipeline @Housing.com]]></title>
            <link>https://medium.com/engineering-housing/css-pipeline-shift-to-compile-time-css-in-js-ea89b60a68ad?source=rss-5706633ede31------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea89b60a68ad</guid>
            <category><![CDATA[css]]></category>
            <category><![CDATA[css-cascade]]></category>
            <category><![CDATA[css-specificity]]></category>
            <category><![CDATA[linaria]]></category>
            <category><![CDATA[emotionjs]]></category>
            <dc:creator><![CDATA[Naman Saini]]></dc:creator>
            <pubDate>Thu, 16 Mar 2023 11:15:16 GMT</pubDate>
            <atom:updated>2023-03-16T11:15:16.984Z</atom:updated>
            <content:encoded><![CDATA[<p>Part 1: Emotion to Linaria</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*DYKkfB06lvTr7_L3TM9Y4A.jpeg" /></figure><h3>What’s it about?</h3><p>CSS in JS has been in the frontend ecosystem for a few years now. We were no different, and adopted EmotionJS 3 years ago. At that time we did some performance benchmarks to compare a few CSS-in-JS libraries primarily styled-components &amp; Emotion. CSS-in-JS provides various benefits, to name a few:</p><ol><li>Critical CSS extraction during SSR</li><li>No global namespace collisions</li><li>Dynamic style interpolations</li><li>Theming</li><li>Automatic handling of css specificity issues</li><li>Automatic handling of cascading issues [declaration order precedence in CSS]</li></ol><p>All of these combined were actually responsible for the rise of CSS-in-JS libraries.</p><h3>What went wrong?</h3><p>Over the last 3 years things have changed, we noticed that the benefits of EmotionJs [or any other runtime CSS-in-JS library] come at a cost, a performance cost. These libraries parse CSS at runtime which was becoming a performance bottleneck. <a href="https://github.com/reactwg/react-18/discussions/110">Release of React 18</a>, further made things complicated for these libraries. Within this period, there has been a new tread compile time <em>CSS-in-JS libraries. </em>Most of these libraries extract CSS from JS at build time, thus remove the runtime performance bottleneck, but that also brings in some limitations:</p><ol><li>Critical CSS extraction — is no longer efficient</li><li>Dynamic Style interpolation — not possible in a few libraries, partially possible in few others [with help of CSS variables]</li><li>Theming — possible with help of CSS variables</li><li>CSS specificity &amp; cascading issues — possible with <a href="https://css-tricks.com/lets-define-exactly-atomic-css/">atomic css</a></li></ol><p>We explored a few such libraries <em>[primarily Linaria and compiled]. </em>And found that Linaria served most of our use cases well.</p><h3>What worked for Linaria?</h3><ol><li>Airbnb recently adopted it. <a href="https://medium.com/airbnb-engineering/airbnbs-trip-to-linaria-dc169230bd12">Here’s their journey</a>.</li><li>It’s syntax for the most part is very similar to how we wrote EmotionJs. Therefore, it meant a lesser learning curve for our team.</li><li>It supported <a href="https://github.com/callstack/linaria/blob/master/docs/BASICS.md#prop-based-styles">dynamic style interpolations</a></li><li>It supports Atomic CSS</li></ol><p>These reasons were enough for us to consider linaria seriously.</p><h3>Problems?</h3><ol><li>We wanted our migration to be slow. Therefore, we needed to support both Emotion &amp; Linaria in our system at the same time.</li><li>Linaria needs additional CSS pipeline to be setup: MiniCssExtractPlugin, CSS-loader, CSS-Nano, PostCss etc</li><li>Without Atomic, linaria can’t handle the css specificity issues.</li><li>With Atomic, linaria doesn’t generate unique keyframe names, which might lead to conflicts in different animations</li><li>There were a few limitations to dynamic style interpolations and we had to work around them.</li></ol><h3>Solutions!</h3><h4>Supporting both linaria &amp; emotion</h4><p>This was relatively simple. Both emotion and linaria have their own babel-plugins/webpack-loaders. We created a convention, we were earlier using .js extension for all our components. Now we adopted .jsx extension for the components which were using linaria. We changed our babel/webpack configs such that Emotion would only run on the .js files and linaria would run on .jsx files. This helped us achieve complete interoperability. All new components are now written using linaria, while we are slowing migrating existing emotion components to linaria. It’s also possible to call a linaria component from an emotion component and vice versa.</p><h4>Handling css specificity/cascading issues [when not using atomic css with linaria].</h4><p>Consider the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ead2ba24cbdde870346c7e26770151a7/href">https://medium.com/media/ead2ba24cbdde870346c7e26770151a7/href</a></iframe><p>Those coming from Emotion background would expect the button to effectively have a font-size: 14px . Because we have applied the overrideStyle after the defaultStyle . While that is true for emotion, the same can’t be guaranteed for linaria. This problem arises due to CSS’s cascading feature, wherein it doesn’t matter in what order the classnames have been applied to an element, what matters is in what order the styles are declared in the stylesheet. And with modern bundlers it’s very difficult to predict the actual order [its not deterministic]. How Emotion solved this problem is out of scope of this article [but let’s say runtime CSS-in-JS libraries have an edge here]. Anyway, this was a problem for us, we don’t want non-deterministic behaviour on production.</p><p>Therefore, we created a babel plugin and modified our code like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1cac22b5a0e5612cb88f83fc95bec94e/href">https://medium.com/media/1cac22b5a0e5612cb88f83fc95bec94e/href</a></iframe><p>For the overrideStyle instead of using the normal css tagged template literal we started using a custom overrideCss tagged template literal, which is essentially css as overrideCss . What’s the change then?</p><p>Well, our babel plugin looks for all overrideCss tags and modifies them like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e81aa4a10a8dc546b8240931bec5cc6/href">https://medium.com/media/4e81aa4a10a8dc546b8240931bec5cc6/href</a></iframe><p>How would this help? We increased the CSS specificity. Selectors with higher specificity override the ones with lower specificity.</p><p>What’s the need for a babel plugin, couldn’t we write this manually? Obviously we can. But we felt this overrideCss might be more intuitive to developers rather than randomly enclosing styles in &amp;&amp; {}</p><blockquote>Note: This won’t solve all our problems in this context. There might be cases where we might need more than 2 levels of overrides, in such cases, we might consider modifying our plugin like so:</blockquote><pre>overrideCss(3)`font-size: 12px;`</pre><h4>Handling Keyframes [if using Atomic with Linaria]</h4><p>For some reasons linaria doesn’t generate unique keyframe names in atomic mode, which is a cause of concern for us. While, we couldn’t find a solution around this, we created a custom postcss-plugin which ensured that the final CSS output shouldn’t contain more than 1 keyframe with same name and different content</p><h4>Creating a CSS Pipeline</h4><p>This is how linaria works:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eed011da8e98028f8db841f260ec0ac9/href">https://medium.com/media/eed011da8e98028f8db841f260ec0ac9/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b1cd7a11b9af6cd92c4557c255e5777b/href">https://medium.com/media/b1cd7a11b9af6cd92c4557c255e5777b/href</a></iframe><ol><li>For the input component.js file linaria creates a corresponding component.linaria.css file with extracted css.</li><li>It also adds a require for this particular file in the original component.js file.</li><li>It also modifies the declarations of all css tagged template literals, replacing them with <em>actual generated unique classname strings</em></li></ol><p>This is where linaria stops. But this alone won’t work. We need to do the following</p><ol><li>add a CSS-loader to webpack config. Which can understand all require/import statements. because webpack by default just works for js/json files</li><li>For production mode you might want to do additional optimisations using postcss.To name a few autoprefixer [with appropriate browserlist config], cssnano</li><li>Then probably use MiniCssExtractPlugin or style-loader to actually load the styles</li></ol><p>All of this is pretty standard.</p><h3>What else did we do?</h3><ol><li>enforcing mobile first styles — we wrote a postcss plugin which ensured only a whitelisted set of media queries were allowed, so that we could enforce mobile first styles — discussed in <a href="https://medium.com/engineering-housing/css-pipeline-optimising-css-part-2-fdac57b02b21">Part 2</a> of this series</li><li>As a part of dead code elimination we took an opinionated choice &amp; filtered out desktop specific media queries from our mobile builds. More on this in the <a href="https://medium.com/engineering-housing/css-pipeline-optimising-css-part-2-fdac57b02b21">Part 2</a> of this series</li><li>We got into an experimental mode &amp; tried @linaria/atomic with various custom modifications — <a href="https://medium.com/engineering-housing/css-pipeline-experimentation-with-linaria-atomic-9e32747a69ab">Part 3 </a>&amp; <a href="https://medium.com/engineering-housing/css-pipeline-optimising-css-part-5-4a5a9262e417">Part 5</a> of this series</li><li>We were facing few scalability issues with MiniCssExtractPlugin, that’s when we experimented and created our own version of isomorphic-style-loader . — <a href="https://medium.com/engineering-housing/style-loader-using-react-18-streaming-and-babel-plugin-3e0ca8726f58">Part 4</a> of this series</li></ol><p>That’s all folks! Please do share your valuable feedback &amp; keep following this space for more such content.</p><p>This is a <strong>first in the series of articles on</strong> our CSS Pipeline.</p><p>Check out the other articles of this series: <a href="https://medium.com/engineering-housing/css-pipeline-optimising-css-part-2-fdac57b02b21">Part 2</a>, <a href="https://medium.com/engineering-housing/css-pipeline-experimentation-with-linaria-atomic-9e32747a69ab">Part 3</a>, <a href="https://medium.com/engineering-housing/style-loader-using-react-18-streaming-and-babel-plugin-3e0ca8726f58">Part 4</a>, <a href="https://medium.com/engineering-housing/css-pipeline-optimising-css-part-5-4a5a9262e417">Part 5</a></p><p>Once again shout out to the ones who helped achieve this: <a href="https://medium.com/u/975fcb904f98">Dhruvil Patel</a>, <a href="https://medium.com/u/1d336d175579">sachin agrawal</a>, <a href="https://medium.com/u/8df7197590c9">Nikhil Verma</a>, <a href="https://medium.com/u/687ab3250312">Sachin Tyagi</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea89b60a68ad" width="1" height="1" alt=""><hr><p><a href="https://medium.com/engineering-housing/css-pipeline-shift-to-compile-time-css-in-js-ea89b60a68ad">CSS Pipeline @Housing.com</a> was originally published in <a href="https://medium.com/engineering-housing">Engineering @ Housing/Proptiger/Makaan</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Icons — A Big Mystery for Web browsers]]></title>
            <link>https://medium.com/engineering-housing/icons-a-big-mystery-for-web-browsers-4d8db9b6fadb?source=rss-5706633ede31------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d8db9b6fadb</guid>
            <category><![CDATA[housing]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[browsers]]></category>
            <category><![CDATA[icons]]></category>
            <dc:creator><![CDATA[Naman Saini]]></dc:creator>
            <pubDate>Fri, 06 May 2022 08:06:21 GMT</pubDate>
            <atom:updated>2022-05-10T06:48:35.215Z</atom:updated>
            <content:encoded><![CDATA[<h3>Icons — A Big Mystery for Web browsers</h3><figure><img alt="Cover Image" src="https://cdn-images-1.medium.com/max/1024/1*3kOCWN2N8yQPAMU5IV48gg.jpeg" /></figure><p>When we are designing User Interfaces, we certainly always use <strong>icons</strong> to make it visually appealing ,user friendly, and also save some canvas space by not showing text and replacing them with self explanatory icons.</p><p>There are multiple ways of adding Icons, each having it’s own pros and cons.</p><blockquote>I wanted to use the approach that would, minimise my effort while coding 😝 , is best for website performance in comparison to other techniques and doesn’t degrade end user experience, for our website <strong>housing.com</strong>.</blockquote><h3>1. Use PNG/JPEG images:</h3><p>We can have icons as JPEG/PNG images, and place them by using &lt;img&gt; tag.</p><figure><img alt="Sample code using image tag" src="https://cdn-images-1.medium.com/max/564/1*lJmydQJkjAQlLcu7Xq-hOg.png" /></figure><p>Biggest pro of this method is that it is a quite simplistic approach. Whatever icons we need we will simply import their images.</p><p>But by using this method, there would be a dramatic loss in quality when same icon image is scaled at different sizes and hence would require us to have multiple images for different screen resolutions. This means extra resources to load. Additionally, if we wanna change icons on hover/click, it would require a new network call which may result in slow UI change for people with slow internet. Also, there would be a lot of network calls just after page load when we require multiple icons in our first fold.</p><h3>2. Using image sprites:</h3><p>An image sprite is merely a collection of separate individual images put together to form a single image. Image sprite arranges all icons in a single GIF or PNG file and is loaded as a CSS background image.</p><figure><img alt="Sprite Image" src="https://cdn-images-1.medium.com/max/262/1*f6RfKeCNwuvwC4kPi4RC5A.png" /></figure><p>By adjusting the CSS background property, only the required icon is displayed. eg. in the below snippet, we load spriteImage.png and display the icon which was 20px in horizontal and vertical direction both.</p><figure><img alt="Code for css background property" src="https://cdn-images-1.medium.com/max/553/1*Dxex40Viieyp0D2gYxC_Vg.png" /></figure><p>In earlier method we required separate network calls when we require same icon at different resolutions, or changing icon on hover/click, or for completely different icons. All these network calls are eliminated by using image sprite as we can include all icons we would require in the same sprite.</p><p>But, even in this method we would require same icon at different resolutions to be included in the sprite, as only one image can’t scale up and down. Additionally, using sprite means we are downloading a large file with multiple icons which might include icons we don’t require at that particular time.</p><h3>3. Using Icon Fonts:</h3><p>Icon fonts are in essence simple text and are included as pseudo elements (:before or :after).</p><p>Major pros of using icon fonts is that they are able to scale up perfectly to any resolution without any degradation or loss of visual quality. We can also change size/color using CSS properties like font-size, color for the same. There are a lot of websites offering free icon font packages eg. FontAwesome, IcoMoon, FlatIcon, etc.</p><figure><img alt="css. changing size and color of icon font" src="https://cdn-images-1.medium.com/max/227/1*rI1PDbjM4LzB8H72pf-q7w.png" /><figcaption>Changing attributes of icons using CSS properties</figcaption></figure><p>Many a times we may require our icons to be multi-color and icon fonts do not support multi-color icons as of now. Moreover, icon fonts suffer some browser anti-aliasing techniques when scaled.</p><h3>4. Using SVG Images:</h3><p>SVG stands for Scalable Vector Graphics. SVG is used to define vector-based graphics for the Web.</p><p>As the name suggests, SVG offer an unmatched ability to be scaled to any size without any shred of quality degradation and it also offers better anti-aliasing than Icon fonts. Moreover, we can edit, color, or animate <strong>each individual bit</strong> of an SVG icon, unlike icon fonts. Since SVG icons are just a block of code, their sizes are much lower to that of image based PNG JPEG icons. They also offer better accessibility, better animations than icon fonts.</p><p>We can further use SVGs in 3 different ways:</p><h4>a. External SVG</h4><p>This is basically storing SVG in an individual different file with the extension .svg, and including it in our project using Image or Object HTML tags.</p><figure><img alt="external svg code" src="https://cdn-images-1.medium.com/max/568/1*T2AxlNEr89JhlM0VzFK8_A.png" /><figcaption>Sample HTML code with external SVG</figcaption></figure><p>External SVGs are cached by browser. Hence, if we require same SVG multiple times, we can use the cached one, it won’t cause network load. Also, if we need to change an SVG later then we can just change one file and it would reflect change in all places used. By using them we also don’t see multiple lines of irrelevant code in our HTML files. These all are actually cons we would face in inline SVG(as we will see next).</p><p>Again, as with simply using PNG/JPEG icons, it triggers multiple network calls for each SVG required. Moreover, SVG attributes like fill property can’t be modified when using external method. So if we wanna change color on hover/click we would have to get a separate SVG file for the same which would mean another network call.</p><h4>b. Inline SVG</h4><p>Inline SVG means placing SVG code block directly into our HTML/JSX code.</p><figure><img alt="Sample code for inline SVG" src="https://cdn-images-1.medium.com/max/998/1*wwlMORr36E3Lm7lExu-72Q.png" /><figcaption>Sample JSX code with inline SVG</figcaption></figure><p>Inline SVG benefits us by saving the extra network call as in the case of external SVG. We can also use css ‘fill’ property and change the color.</p><figure><img alt="sample css fill code" src="https://cdn-images-1.medium.com/max/193/1*H1jsAT_Vyqn5up499xFyEg.png" /><figcaption>Changing SVG icon color to red</figcaption></figure><p>Downside of using Inline SVG is that they clutter our HTML code and in case we have to use the same icon at multiple places (eg. fancy bullet icon in an unordered list) we will have to write the same SVG code again and again.</p><h4>c. Importing SVG directly as a component (React)</h4><p>If we are using create-react-app for our project, we can directly import SVG file as a component, and call that component</p><figure><img alt="Using SVG icon as a component" src="https://cdn-images-1.medium.com/max/1024/1*tLShF5aY_jD-qf-9sGg-1A.png" /><figcaption>React Code for using SVG icon as a component</figcaption></figure><p>This basically inserts our SVG as inline. Hence it enjoys all the pros of Inline SVG, and due to the way of it’s implementation — also eliminates all the cons of Inline SVG as well.</p><p>If we are not using create-react-app, then we can also use SVGR package for the same. First install SVGR using any package installer, here we used npm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*v_4wf9AejR_SMkZJoZ3yqw.png" /><figcaption>Installing SVGR</figcaption></figure><p>As this is a Webpack loader. We will config the webpack.config.js file with it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*AtRPjbbbiltRBZSbpHlIcA.png" /><figcaption>Adding support in webpack config</figcaption></figure><h4>c. SVG Sprite</h4><p>This is basically including all SVGs in our project on a single go, and using one when we require. It is basically combining pros of inline and external method. An SVG sprite is also a code block. Below snippet shows a sample SVG sprite. We extract only &lt;path&gt; part from our original icon SVG and wrap it in &lt;symbol&gt; tag. This whole code is wrapped in &lt;defs&gt; tag which is further wrapped in &lt;svg&gt; tag. We can automatically create this SVG using icomoon. We can also use the sample code provided on/by <a href="https://svgsprite.com/tools/svg-sprite-generator/">https://svgsprite.com/tools/svg-sprite-generator/</a> or by writing a simple program which does exactly the same.</p><figure><img alt="Sample SVG Sprite" src="https://cdn-images-1.medium.com/max/1024/1*cllL17KGVr_RZbpBu1jHWA.png" /><figcaption>Sample SVG Sprite file</figcaption></figure><p>After making this sprite, we can simply include the icon we want from our HTML file. In below snippet we can change ‘id’ variable to the id of the icon we wrote in SVG sprite eg. first SVG has an id of ‘icon-buyProperties’. We can also change fill color of that by styling this SVG tag using css.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*AGNm_pwc88c99X58vB7Piw.png" /><figcaption>JSX code for including a specific SVG from it’s sprite container</figcaption></figure><p>By using SVG sprite we can customise SVG attributes like ‘fill’ according to our need as with Inline SVG. It also doesn’t make network call for each SVG required as everything is already loaded on first load. Also size of SVG sprite is much smaller than each SVG individually combined. In my testing for a sample of 11 SVGs, 35256 bytes were loaded when using each SVG externally, while only 28996 bytes were loaded when using sprite. Moreover, this sprite file is also cached by browser (in a scenario where we reload the page and and require the file again).</p><p>Con of normal PNG/JPEG repeats here — We are loading even those SVGs which we don’t require on our first fold screen, in our first network call.</p><p>Now the surprise, all issues related to separate network calls were solved in HTTP 1.1 protocol, as 1.1 supports parallel network calls(6 requests at a time), and it won’t choke the server like it does in 1.0. Moreover, HTTP 2.0 doesn’t have any limit for parallel network calls. Hence, this problem isn’t one of our concerns as we at housing.com are supporting HTTP 2.0 protocol.</p><p>We didn’t go with JPEG/PNG image or their sprites due to their lack of scalability.</p><p>We were in past using icon fonts, as it’s cons weren’t much of a concern earlier, but now there is a need of multi-color icons and hence we can’t continue with icon fonts for the same. Hence, only option is to go with SVG.</p><p>I didn’t want to clutter our JSX code with irrelevant SVG code by going inline. Additionally, repeating the same code for multiple places in case same icon is showing multiple times, increases file sizes unnecessarily.</p><p>I wanted to use SVG by importing it as a React Component, but we don’t use create-react-app, and adding support of SVGR was giving some trouble as we already have some image compression support for SVG in place and these two weren’t able to work together. Hence, had to drop this approach.</p><p>External SVG seemed a better option as this also helps to load only those SVGs which are currently required, whereas sprite would have included them all at once. Though with this we won’t be able to change fill color properties of SVG using CSS.</p><blockquote>Hence, we will now be using a mix of external and SVG sprite depending on the use case. eg. if we want to change color or want completely different SVG icon on hover/click for few icons, we will use sprite only for those ones to avoid lag in slow networks, otherwise we will be using external SVGs for the rest of them.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d8db9b6fadb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/engineering-housing/icons-a-big-mystery-for-web-browsers-4d8db9b6fadb">Icons — A Big Mystery for Web browsers</a> was originally published in <a href="https://medium.com/engineering-housing">Engineering @ Housing/Proptiger/Makaan</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>