<?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 Prateek Bhatnagar on Medium]]></title>
        <description><![CDATA[Stories by Prateek Bhatnagar on Medium]]></description>
        <link>https://medium.com/@prateekbh?source=rss-d5243409b984------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*cvRIepyYmL1xD1BLATLGRQ.jpeg</url>
            <title>Stories by Prateek Bhatnagar on Medium</title>
            <link>https://medium.com/@prateekbh?source=rss-d5243409b984------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 03:29:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@prateekbh/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[Using Brotli with Preact — CLI 3]]></title>
            <link>https://medium.com/progressive-web-apps/using-brotli-with-preact-cli-3-ca03125b1e2b?source=rss-d5243409b984------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca03125b1e2b</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Prateek Bhatnagar]]></dc:creator>
            <pubDate>Thu, 18 Apr 2019 23:27:56 GMT</pubDate>
            <atom:updated>2019-07-26T18:19:04.003Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mUoL7Gs0x4gkPufOD6cM7w.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/phUtWl8RyFE?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Brett Jordan</a> on <a href="https://unsplash.com/search/photos/delivery?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Using Brotli with Preact — CLI 3</h3><h4>Preact CLI is a PWA/SPA scaffolding tool which uses tools from Preact Ecosystem to build the same.</h4><p>If you’ve ever done any web performance tasks of any web content or looked at any performance report from any tool than you would know that most content sent over wire is compressed before sending it to the browser. As of now most of this is done in the form of <a href="https://betterexplained.com/articles/how-to-optimize-your-site-with-gzip-compression/">GZip</a> compression.</p><p>As a web developer you build your web app using any tool/framework etc and upload to any hosting provider. After this, these web servers upon receiving a request for any asset compress the response using GZip and send it to the client who decompresses it using the algorithm mentioned in content-encoding response header.</p><p>A similar but latest algorithm in this space is Brotli compression algorithm. It has shown to improve compression ratios for web content and is a successor of gzip and zopfli algorithms.</p><blockquote>This new format allows us to get 20–26% higher compression ratios over Zopfli. In our study ‘Comparison of Brotli, Deflate, Zopfli, LZMA, LZHAM and Bzip2 Compression Algorithms’ we show that Brotli is roughly as fast as zlib’s Deflate implementation. At the same time, it compresses slightly more densely than LZMA and bzip2 . — <a href="https://opensource.googleblog.com/2015/09/introducing-brotli-new-compression.html">Google’s Official Blog</a></blockquote><p>A better compression means less bytes to download for users resulting in faster download times and earlier time to interactivity and other metrics.</p><blockquote>Important: However there are lesser bytes to download please remember that after decompression it is still same amount of code and thus resulting in same parse and eval time of the script.</blockquote><p>Sadly, the support for the same is not really great from a lot of service providers. If you upload your web app without any changes major CDNs and hosting providers still use GZip out of the box with no support for Brotli at all.</p><p>Thanks to Service workers we have a good control to what resources we request from the network and switch what was originally requested by the browser.</p><p>In Preact-CLI we have a flag --brotli which automatically generates brotli compressed assets for all the javascript files. This means that all the generated javascript files also have a .js.br files next to them. These files are never requested by your web app on its own.</p><pre>preact build --brotli</pre><p>But the service worker installed by the scripts with type=module can be sure that they also support brotli compression. Check the following two links to be sure</p><p><a href="https://caniuse.com/#feat=brotli">https://caniuse.com/#feat=brotli</a></p><p><a href="https://caniuse.com/#feat=es6-module">https://caniuse.com/#feat=es6-module</a></p><p><strong>Without this flag</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/1*VWV_GXeC04zMrnmwtEfyDA.png" /><figcaption>How a normal request response would work</figcaption></figure><p><strong>With this flag</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*EdRZuWDAqsrGi4ZlGEcLOQ.png" /><figcaption>A request with this service worker in between is intercepted and converted to a `.js.br` file request</figcaption></figure><p>This service worker precaches the first party javaScript by precaching .js.br files. Whenever a page requests a first party .js file, service worker responds with the contents of corresponding brotli file.</p><p><strong>Note: </strong>The<strong> </strong>decompression of the content happens before the contents are handed over to the service worker. Thus you have to make sure that all .br files are served with correct headers of content-encoding: br.</p><p>Most services allow you to do this by some or other config files.</p><ul><li>Netlify has _headers file where you can specify this custom header. <a href="https://www.netlify.com/docs/headers-and-basic-auth/">https://www.netlify.com/docs/headers-and-basic-auth/</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*qsrmRgbbJeu1hkKd8zNJPg.png" /></figure><p>With these custom headers and the service worker precaching of Preact CLI you’re all set to take the benefit of Brotli compression without waiting for your provider to enable the same.</p><p>One such demo app is deployed at <a href="https://material-cli.netlify.com/">https://material-cli.netlify.com/</a>. When you launch the app you will observe that all the precached files requested by the service worker are actually brotli compressed javascript files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qCkR_YMl9Z-HAYbzvpx3Wg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*isivrJaVH1NbLspHKVS1Aw.png" /><figcaption>Before and After enabling Brotli compression in preact-cli.</figcaption></figure><p>We’re keen to hear feedback/issues and anything you wanna say on our github issues <a href="https://github.com/developit/preact-cli/issues">page</a>.</p><p>Cheers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca03125b1e2b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/progressive-web-apps/using-brotli-with-preact-cli-3-ca03125b1e2b">Using Brotli with Preact — CLI 3</a> was originally published in <a href="https://medium.com/progressive-web-apps">Progressive Web Apps</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My experience writing a webpack’s child compiler plugin.]]></title>
            <link>https://medium.com/@prateekbh/my-experience-writing-a-webpacks-child-compiler-plugin-a1237c175947?source=rss-d5243409b984------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1237c175947</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[webpack]]></category>
            <dc:creator><![CDATA[Prateek Bhatnagar]]></dc:creator>
            <pubDate>Fri, 21 Sep 2018 05:09:35 GMT</pubDate>
            <atom:updated>2018-09-21T05:09:35.164Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p-mRmN_agWi5vPl1PoqHRg.jpeg" /></figure><h4>This is me sharing my experience of writing my first webpack plugin and the things that came as learning out of it. Since its an experience-based blog post, I do not intend this to make a statement towards webpack’s DX. This was my first ever webpack plugin so everything down below might sound like big disaster to you. Please feel free to point me in a better direction.</h4><p>A few weeks ago I took up a task of writing a webpack plugin. I wanted this plugin to spit out mirror copies of the javascript assets generated by webpack but with a different babel configuration.</p><blockquote>More context: With browsers supporting script module/nomodule we should ship less transpiled code to users today. Read more in this article from <a href="https://medium.com/u/af9c5528a8ab">Phil Walton</a> <a href="https://philipwalton.com/articles/deploying-es2015-code-in-production-today/">https://philipwalton.com/articles/deploying-es2015-code-in-production-today/</a></blockquote><p>So my idea was to have a webpack plugin which could sit in your webpack configuration and transpile your files using the <a href="https://babeljs.io/docs/en/babel-preset-env">babel-preset-env</a> with the target set to <a href="https://babeljs.io/docs/en/babel-preset-env#targetsesmodules">esmodules</a>. So all that’s left will be to add a &lt;script type=moduletag.</p><p>I started by reading a few blogs, some articles(some outdated/some still relevant) to figure out how to build a webpack plugin. I found a few webpack hooks which are called for every asset that webpack encounters while parsing your code etc. While doing the reading exercise I stumbled on the concept of <em>childCompiler</em>, this sounded like a subprocess kinda thing and “sounded” to be the thing that I’d want. But this had no dedicated documentation on what it is, its pros/cons, when to use etc on the webpack docs site. Since I couldn’t find anything else I decided to give it a try. The only help from the internet was this stackoverflow explanation from <a href="https://medium.com/u/577c0e279fd5">Arthur Stolyar</a> <a href="https://stackoverflow.com/questions/38276028/webpack-child-compiler-change-configuration">https://stackoverflow.com/questions/38276028/webpack-child-compiler-change-configuration</a>.</p><p>So after realizing that Child compilers are exactly like sub processes inside the main webpack process I was convinced that this the thing I could use to re-run the entire codebase through a different babel setting.</p><p>So I just tried following the above stackoverflow explanation and created a basic child compiler as follows:</p><p><strong>Step 1: </strong>Create a class with apply method to tap into webpack’s plugin cycles</p><pre>class MyPlugin {<br>  constructor() {...}<br>  apply(compiler) {<br>    compiler.hooks.make.tapAsync(PLUGIN_NAME, (compilation, cb) =&gt;<br>      {<br>        // all logic goes here<br>      }<br>  }<br>}</pre><p>In the above example we hooked our plugin into the plugin system of webpack and our apply method will be called with the main compilation as the argument.</p><p><strong>Step 2: </strong>Using main compilation to instantiate a childCompiler and execute it.</p><pre>//inside apply function<br>const childCompiler = compilation.createChildCompiler(PLUGIN_NAME, outputOptions, plugins);</pre><p>The above method takes 3 parameters,</p><ol><li>The name of the compiler</li><li>The output options for the files generated inside the child compilation(same as the webpack config).</li><li>The array of plugins you’d want to execute on this childCompilation.</li></ol><p>This here is a pretty powerful API, I used this to rename my generated files from x.[chunk].jsto x.[chunk].esm.js. Also one could add or remove the plugins from the actual config for the child compilation. e.g. In my usage I add a WebpackDefinePlugin to add an env variable <em>isESM</em> so that I could add conditionals for the other build.</p><blockquote>Note: In order to access the parent configuration use compiler.options from the compiler object passed in the apply method params.</blockquote><p><strong>Step 3: </strong>Add entry points</p><p>If you look closely, in the <em>createChildCompiler</em> compiler we only gave output options of our config. This means that the child compiler has no knowledge of the entry points, thus we’d have to specify it explicitly.</p><p>There is a webpack internal plugin exactly for this known asSingleEntryPlugin. So the following code could just take all the entry point from the parent config and add them as is to the child compiler.</p><pre>Object.keys(compiler.options.entry).forEach(entry =&gt; {         <br>  childCompiler.apply(<br>    new SingleEntryPlugin(<br>      compiler.context, <br>      compiler.options.entry[entry], entry<br>    )<br>  );      <br>});</pre><p>If you run this childCompiler at this point you’ll see that you are generating mirror copies of the original assets.</p><blockquote>IMPORTANT: Do not forget to change the filename in the createChildCompiler call, else you’ll override the actual files.</blockquote><p><strong>Step 4: </strong>Discover that the chunks are not being fetched.</p><p>If you try to run an app with the new files generated, you’ll observe that the entry point bundle works fine but it is not fetching the chunks over the network!!!</p><p>After some searching I came to know about another internal plugin which actually adds the code to fetch the chunks over the network JsonpTemplatePlugin. And here’s the catch: simply adding this plugin to your plugins array will not make it work. Why? I really don’t know the reason and couldn’t find any documentation about these special plugins anywhere on the documentation site.</p><p>So in order for this plugin to work you need to apply it to the compiler:</p><pre>childCompiler.apply(new JsonpTemplatePlugin());</pre><p>And that should make the chunks working.</p><p><strong>Step 5: </strong>Tell parent compiler about errors, assets and named chunks</p><p>So even if you don’t do this it might work fine with you as the files are generated and you are free to use them. However if any other plugin(say HtmlWebpackPlugin) is trying to know the output, your additional assets will not be visible to it. In a nutshell you have to tell the parent compiler about the assets and named chunks you generated</p><pre>compilation.assets = Object.assign(childCompilation.assets,              compilation.assets);</pre><p>Please use the additionalAssets hook of the parent compilation to make sure you dont end up in a race condition with other plugin.</p><p><strong>Step 6: </strong>Performance plugins</p><p>After playing with this plugin I realized any plugin in my config in the optimization section is also not being applied. Thus I went back and looked for specific plugin. Seems like webpack’s main compiler goes over the specified config and apply the plugins one by one see here <a href="https://github.com/webpack/webpack/blob/9f0056b10d6997fd8e1472fec4b8c84b5d6b1db7/lib/WebpackOptionsApply.js#L322-L373">https://github.com/webpack/webpack/blob/9f0056b10d6997fd8e1472fec4b8c84b5d6b1db7/lib/WebpackOptionsApply.js#L322-L373</a></p><p>The above code goes through your config and applies it to the main compiler. It did kinda felt weird though that the same was not copied over from parent compiler to child compiler or there is not a friendlier function to which I could pass the original config and expect the same plugins to be applied on my compiler.</p><p>Hope this would have be useful for anyone who is writing a child compiler for the first time.</p><p>Here’s the github link for the finished work: <a href="https://github.com/prateekbh/babel-esm-plugin#readme">https://github.com/prateekbh/babel-esm-plugin#readme</a></p><p>Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1237c175947" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Shared elements transitions for Web]]></title>
            <link>https://medium.com/@prateekbh/shared-elements-transitions-for-web-6fa9d31d4d6a?source=rss-d5243409b984------2</link>
            <guid isPermaLink="false">https://medium.com/p/6fa9d31d4d6a</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[animation]]></category>
            <category><![CDATA[preact]]></category>
            <category><![CDATA[web-animation]]></category>
            <dc:creator><![CDATA[Prateek Bhatnagar]]></dc:creator>
            <pubDate>Tue, 24 Apr 2018 02:28:07 GMT</pubDate>
            <atom:updated>2018-04-24T16:18:58.743Z</atom:updated>
            <content:encoded><![CDATA[<h4>This blog post is heavily inspired by posts from <a href="https://medium.com/u/c3bb5bfaf69e">Jiří Otáhal</a>(<a href="https://medium.com/react-native-motion/transition-challenge-9bc9fdef56c7">post</a>) and <a href="https://medium.com/u/5dd0a232236e">Narendra N Shetty</a>(<a href="https://medium.freecodecamp.org/shared-element-transition-with-react-native-159f8bc37f50">post</a>), so big thanks to them before I begin. Also while these two posts focus on react-native, my post is to do the same and tackle the problems in this area on web.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*tW8eHQLHLkGGS4MY2lQkKw.gif" /><figcaption>credit: blog.advids.co</figcaption></figure><p>I’ve always been fascinated with such shared element transitions across native apps realm. They’re fluid, eye catching and also transition the user’s attention very well to the next route. I also saw the same happening for react-native, because of its amazing animation API and the peer pressure from native platforms(I guess). But when it comes to web why isn’t anyone doing it? I tried to dig in, find the tough parts and sketch a pattern for building routes that could make transition routing super easy and scalable for <a href="https://medium.com/@NeotericEU/single-page-application-vs-multiple-page-application-2591588efe58">SPA</a>s to create and maintain.</p><blockquote>For those who are new to shared element transitions, they are animations of an element from one route to another; while moving to a different route/screen/page etc e.g.: <a href="https://bit.ly/2HVHtk7">https://bit.ly/2HVHtk7</a></blockquote><p>A lot of people I talked to, also had a thinking that since it’s already once built with react-native it should be easy to port. That is somewhat true as you can re-use your code, but there can be some rough edges if you think about how a browser behaves. Web ergonomics is different in many ways as compared to a native app, e.g.</p><ol><li>Your user can enter in your app from literally any route which is less likely(but not impossible for native apps) , so you need to be ready for a shared element transition or a normal page appearance at all routes. 🤷‍</li><li>Back button 😢. Unlike native apps, you don’t get to control back button’s behavior. Hence, you will need to be prepared to do exit animation even then your route/app doesn’t know about it.</li><li>Lazy loading 😕. You know your web app is not installed from a play-store/App store, it’s something that user downloads on runtime. Although this is one of the greatest power of web, this can cause erratic and unseen behavior for shared element transitions if the route is not in memory to transition into.</li></ol><p>In this blog I’ll take on similar kind of challenge and would like to write a small 3 route app that should make sense to be extensible to be a part of a complete bigger app, and not just a demo thing.</p><p>By this means, I’ll try to be generic in my approach so that this may apply to more and more frameworks/libs and not just one and also will incorporate more realistic challenges like: retaining scroll positions, ability to start from any route instead of just one etc.</p><p>Here are two sample animations that we will rebuild for web in this blog post</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*ofxjM3jcQr4aa22AbjK5Ag.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*RD9uK5HEDcLqPb75Rz7SDw.gif" /><figcaption>Sample shared element transitions</figcaption></figure><h3>How will we do the shared element</h3><p>Every shared element transition is a three part animation in the pattern we’ll follow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/410/1*8-Bc3hz5qU69brc8hh8eHw.gif" /></figure><ol><li>User taps on a card and the existing route will handover it and its position to the <em>GhostLayer*</em> class, as well as disappears the card which was tapped on.</li><li><em>GhostLayer </em>will render the <em>SharedElement</em> on the given position.</li><li>As the new Route mounts/initializes, it will give the destination position to the <em>GhostLayer,</em> which will return a Promise. This promise will be resolved when the animation of <em>SharedElement </em>to the destination will complete.</li></ol><p>After this the new route will show the <em>SharedElement’s </em>clone on itself and <em>GhostLayer </em>will remove the <em>SharedElement.</em></p><p><em>*GhostLayer: </em>Imagine this as a div with highest z-index covering all of the screen always, which is active only when <em>SharedElement </em>is present in it.</p><h3>Entry Animation</h3><p>To do the <em>SharedElement </em>animation we will do entry animation on every route. Every entry animation will begin after adding a class to the route, this will give us the flexibility of deciding when to start the entry animation.</p><p>In case of direct entry on the page, we will immediately start the animation and in case of <em>SharedElement </em>transition we will wait for the animation on the <em>GhostLayer</em> to finish.</p><p>The way I will do it in my app is that, I will send the destination position of the <em>SharedElement</em> and <em>GhostLayer</em> will return an animation promise. Upon resolution of this promise, the entry animation of the rest of the page will be played.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d74461aeed16e90b5e7f7c2da80ff707/href">https://medium.com/media/d74461aeed16e90b5e7f7c2da80ff707/href</a></iframe><p>With the above setup, we are good with every page being entry page independent of whether the app is launching from it, or the page is a part of <em>SharedElement </em>transition.</p><blockquote>Tip: It might be a good idea to add contain: strict to avoid triggering any layout trigger from getBoundingClientRect</blockquote><h3>Exit Animation</h3><p>Exit animation on mobile web may take a little more work than the other parts because of the back button we discussed. The problem arise when instead of tapping a UI element, user presses the back button.</p><p>In this case we don’t know which element should be chosen as the <em>SharedElement. </em>In this case I usually take a look at the next url and see if it can tell me about the <em>SharedElement. e.g. </em>If the next URL is <em>‘/details/stock3’, </em>then I can predict that third stock card will be the <em>SharedElement </em>and share its clone to the <em>GhostLayer.</em></p><p>If you’ve cracked the above part, rest of the flow should be kept similar to entry animation. i.e. Add a class that performs exit animation, share the element to the <em>GhostLayer,</em> and let the router mount the new route.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e0664357a6ff2c2b4e75bdb28e68207/href">https://medium.com/media/7e0664357a6ff2c2b4e75bdb28e68207/href</a></iframe><h3>App Code</h3><p>Using the above two discussed stuff, we’ll create a three route app which will do shared element transition amongst it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*cedSSPu82J31nJa4M4xVag.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*M8cb2Evav1rka0TpTRlZRg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*gEGiRBnxyLaT_O-_UqOEpA.png" /><figcaption>Three screens of the app (Stocks listing -&gt; Stocks details -&gt; Profile)</figcaption></figure><p>I am using preact ecosystem/ preact-cli to bootstrap a project and will take it on from there.</p><pre>preact create material transition-challenge</pre><p>After that ☝, I’ll start implementing the routes and extend the router preact-router with <a href="https://github.com/prateekbh/transition-challenge/blob/master/src/components/app.js#L68-L89">preact-transition-group</a> to add a callback ComponentWillLeave which will tell the Component before it leaves where the exit animation can be started.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f4548ca0c2588d326eb6c79ffe0ed0bd/href">https://medium.com/media/f4548ca0c2588d326eb6c79ffe0ed0bd/href</a></iframe><p>The above code shows the extra div which will work as our <em>GhostLayer. </em>I also implemented<em> GhostLayer </em>and<em> </em>implemented the <em>runAnimation </em>and <em>addSharedElement </em>methods.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e14bf06d73131b0e77fba3d4e9c49fe/href">https://medium.com/media/2e14bf06d73131b0e77fba3d4e9c49fe/href</a></iframe><p>Now we just need to connect this to a every route’s componentDidMount and componentWillLeave e.g.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d74461aeed16e90b5e7f7c2da80ff707/href">https://medium.com/media/d74461aeed16e90b5e7f7c2da80ff707/href</a></iframe><h3>Result:</h3><p>Here’s a preview of what I was able to build with this generic pattern altogether.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/224/1*rTqMy1rv--t0FfbiMCl8tQ.gif" /></figure><h3>Summary:</h3><p>So here’s a summary sketch of the pattern I followed to to build this sample app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XGznXFwdMo42_H4Vgu78Pg.png" /><figcaption>Pattern for Shared element transition</figcaption></figure><h3>Extension over this pattern</h3><p>Feel free to extend this pattern by passing a map of element’s clone and their positions instead of just one element and its position. That way you’ll be able to share more than one element transition.</p><p><strong><em>Github:</em></strong><em> </em><a href="http://github.com/prateekbh/transition-challenge"><em>github.com/prateekbh/transition-challenge</em></a></p><p><strong><em>Working app:</em></strong><em> </em><a href="https://transition.surge.sh/"><em>https://transition.surge.sh</em></a></p><p><em>Hope you liked it. For any questions feel free to ping me at </em><a href="https://twitter.com/_prateekbh"><em>twitter</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6fa9d31d4d6a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Code splitting and Server side rendering for preact async routes.]]></title>
            <link>https://medium.com/@prateekbh/code-splitting-and-server-side-rendering-for-preact-async-routes-e8052e08ba22?source=rss-d5243409b984------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8052e08ba22</guid>
            <category><![CDATA[server-side-rendering]]></category>
            <category><![CDATA[pwa]]></category>
            <category><![CDATA[preact]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[preact-router]]></category>
            <dc:creator><![CDATA[Prateek Bhatnagar]]></dc:creator>
            <pubDate>Thu, 08 Feb 2018 19:38:04 GMT</pubDate>
            <atom:updated>2018-02-08T19:38:04.776Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8yz3hkO3ynHV2qYGARynJg.jpeg" /></figure><p>If you’re to create amazing web-based user experiences in the modern era, they need to be fast and interactive in no time. Two key metrics that can help you in doing the same are <em>Time to first meaningful paint(TTFP) </em>and <em>Time to interactivity(TTI)</em>. Both of these rely heavily on how much javascript are you sending down the wire to your user’s machine to parse and execute. This becomes even more critical if in-case you are dealing with a single page app because your javascript bundle size will not only delay your <em>Time to interactivity</em> but also will not render anything on screen till it’s parsed and executed.</p><p>The answer to a faster <em>Time to first meaningful paint </em>is to <em>Server side render</em> your page or the initial view. The benefit this brings in is that your user does not see a blank screen until the time your javascript bundle is downloaded, parsed and executed.</p><p>In this blog, we’ll try to build a small app with two routes, with which we will try to fix the above-said problems. We’ll try to fix the <em>Time to first meaningful paint </em>and the add <a href="http://npmjs.com/package/preact-async-route">AsyncRoute</a> to reduce the jS bundle size and improve the <em>Time to interactivity</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*QA4XYdXTHOmKdnrnm1MzNQ.jpeg" /><figcaption>Our sample’s page with home and user’s page.</figcaption></figure><p>Here is how our root App code looks like at this point:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/30fcbd4eaf92dd47d29ce52ba18b11ac/href">https://medium.com/media/30fcbd4eaf92dd47d29ce52ba18b11ac/href</a></iframe><h4>Server Side rendering</h4><p>Currently, with everything in one js file and no server side rendering our <em>Time to first paint and Time to interactivity </em>is at~3300ms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jIyNPcIlRBGWTY_ZbCCi1w.png" /><figcaption>Note nothing is rendered till all jS is downloaded and parsed #BadUX.</figcaption></figure><p>In order to improve TTFP lets do server side rendering. We use <a href="https://www.npmjs.com/package/preact-render-to-string"><em>preact-render-to-string</em></a>, which makes it really easy to do it.</p><p>Here’s a small sample</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a6021a75da372593e76f2cc78f2686e/href">https://medium.com/media/6a6021a75da372593e76f2cc78f2686e/href</a></iframe><p>In the above example whenever the call comes for an app URL, the app is rendered to a string before sending the response and inserted in the markup. This would exactly replicate the DOM that <em>preact </em>will construct for you on the client side.</p><p>Let’s take a look at the timeline again:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vkN1gUngNOolm2D0LgTnWg.png" /><figcaption>Note first paint is done right as the markup is downloaded and jS is downloaded and parsed later.</figcaption></figure><p>Now our <em>Time to first paint </em>has shifted to @ 2200ms 🙌, but the <em>Time to interactivity </em>is still @ 3550ms. Let’s break this down further and fix <em>Time to interactivity</em> as well.</p><h4>Fixing Time to Interactivity</h4><p>In order to fix TTI, we’ll take a hint from the PRPL pattern. We’ll only send the jS for the current page and make the page interactive with bare minimum jS needed.</p><p>We’ll use AsyncRoute to do code-splitting on our routes using import, which was introduced with ES modules for the browsers. Below is how our sample App.jsx look after this change.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e749a5411374107ecbbaa8dc04d1fd8e/href">https://medium.com/media/e749a5411374107ecbbaa8dc04d1fd8e/href</a></iframe><p>And here’s how our timeline looks now:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vohss1XuNxAf2Mp6ozEHRw.png" /></figure><p>Our <em>Time to interactivity </em>is now at ~3000ms. But uh-oh we broke the server side rendering(see no content below toolbar from SSR☝️)! That’s because preact rendered our app without waiting for the <em>import’s </em>promise to be fulfilled. To fix this, we’ll use a small babel plugin dynamic-import-node-sync which will turn our <em>import </em>statements into webpack older <em>require </em>statements, which are synchronous in nature(include this only for your server’s webpack config).</p><p>We’ll also need to change our loading function to accommodate this and use the callback functionality of AsyncRoute. Here’s how it is done:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e923aa3c53832c5bd6a16d049f32eb1/href">https://medium.com/media/2e923aa3c53832c5bd6a16d049f32eb1/href</a></iframe><p>Lets go back and have a look on our timeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TvarkJ63kdJWSdyWTgYFyA.png" /></figure><p>All looks well, <em>Time to first paint </em>is at~2000ms , <em>Time to interactivity</em> is at ~3000 ms. Except if you look carefully between 3s to 4s you’ll see that the content rendered from server was removed for a while and then re-inserted. This is because when AsyncRoute rendered first it waited to download the route’s bundle and meanwhile showed a blank screen.</p><h3>Highly opinionated Hack 🤘</h3><p>To solve the last problem at our hand, I am doing a very simple hack.</p><ol><li>Before mounting the &lt;App&gt; I’ll take the markup and save in a variable.</li><li>I will maintain a boolean variable which will be set to true after first execution of app.</li><li>If this variable is false, I’ll show the markup from <em>Step 1 </em>as the Loader for the page.</li></ol><p>This way while the first page’s jS bundle is being fetched from the server, you are still looking at the SSRed markup and this scales up-to any number of routes your app might have.</p><p>Here’s a final look on our timeline and the sample code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/379887ea585767471c85a73d09de319c/href">https://medium.com/media/379887ea585767471c85a73d09de319c/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4gmUpr5qk90CtMlKHEuVxg.png" /><figcaption>TTFP @ ~2200ms &amp; TTI @ 2800ms 👍</figcaption></figure><p>The final timeline shows no flush of <em>SSRed </em>content, quick <em>Time to interactivity </em>and <em>Time to first paint.</em></p><p><em>That’s all folks</em></p><p><strong>Related links:</strong></p><ol><li>Async route: <a href="https://github.com/prateekbh/preact-async-route">https://github.com/prateekbh/preact-async-route</a></li><li>Sample code: <a href="https://github.com/prateekbh/preact-async-ssr">https://github.com/prateekbh/preact-async-ssr</a></li><li>Me: <a href="https://twitter.com/_prateekbh">https://twitter.com/_prateekbh</a></li></ol><p><strong>P.S.:</strong> All traces are on Fast 3G and 6x slowed device emulation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8052e08ba22" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Preact-cli and service worker.]]></title>
            <link>https://medium.com/@prateekbh/preact-cli-and-service-worker-2e0f034157e7?source=rss-d5243409b984------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e0f034157e7</guid>
            <category><![CDATA[service-worker]]></category>
            <category><![CDATA[preact]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[webpack]]></category>
            <dc:creator><![CDATA[Prateek Bhatnagar]]></dc:creator>
            <pubDate>Fri, 13 Oct 2017 18:31:01 GMT</pubDate>
            <atom:updated>2018-08-02T15:30:38.694Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://github.com/developit/preact-cli">Preact-cli</a> is a tool to build progressive web apps in a super quick and easy manner using just a few commands. It comes bundled with a pre-configure <a href="https://www.npmjs.com/package/sw-precache-webpack-plugin">sw-precache-webpack-plugin</a> to help you with the same.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t3A-s2eExektSb4S48r0FQ.jpeg" /><figcaption>many tools for making your PWA ace</figcaption></figure><p>Service worker is one of the main pillars of the amazing experience that PWAs bring onto the table. While writing/maintaining service workers by hand can be an exciting task to take up, you might as well want to hand this over to an automated tool like <a href="https://www.npmjs.com/package/sw-precache-webpack-plugin">sw-precache-webpack-plugin</a>. Preact-cli comes preconfigured with the before said <a href="https://webpack.js.org/">webpack</a> plugin and brings you the offline experience out of the box with the very first build of your app.</p><p>This is great for a variety of apps and developers. Zero efforts, Zero friction and your shiny new PWA starts working offline without any hassle; or not 😕.</p><p>Here’s what preact-cli actually brings offline out of the box.</p><ol><li>Your all javascript chunks</li><li>Your all CSS chunks</li><li>Your index.html as fallback to any route in <strong>offline</strong> mode</li></ol><p>☝️all of this mainly brings your <a href="https://developers.google.com/web/fundamentals/architecture/app-shell">app shell</a> offline. So if your entire app is in your jS bundles and you don’t really care about caching your network calls etc(e.g. <a href="https://gabrielecirulli.github.io/2048/">2048</a>, <a href="http://hopon-a72e9.firebaseapp.com/">Hopon</a> etc) then you are good to go 👍.</p><p>But as your application grows you might need custom runtime caching strategies, alter the stuff in your <em>pre-cache</em> entries(<em>imagine you have 24 jS bundles and all being downloaded at the very beginning of the app start, since they are in pre-cache entries of your service worker</em>), immediate claim of your clients etc. This is where the rest of the blog post will focus.</p><p>For the rest of the blog 1st step is this</p><pre>npm i -D <a href="https://www.npmjs.com/package/preact-cli-sw-precache">preact-cli-sw-precache</a></pre><h3>Oh com’on don’t pre-cache everything</h3><blockquote>Problem statement: My app has 10’s of javascript bundle or a few but one of them is really heavy(e.g has a Game engine/Map library in it) so thanks but no thanks to preact-cli’s default pre-caching methodology.</blockquote><p>So your app is growing big n complex, or you have introduced a huge but necessary dependency in one of your route. If you keep going with preact-cli‘s default pre-caching methodology(which is pre-cache all js/css in the build folder), it will start hurting u soon.</p><p><strong>Why? </strong>Imagine your user just landed on your website and service worker got registered. While your current page is trying to make an API call or fetch any image etc, your service worker is downloading that huge dependency or is downloading 10s or 20s of your small per route jS. This will block you user’s bandwidth.</p><p><strong>Solution: </strong>You need to edit the behavior of sw-precache-webpack-plugin in preact.config.js and here’s how you can do that.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a1e2fd758e970b660bcdc0b3838ef2d/href">https://medium.com/media/9a1e2fd758e970b660bcdc0b3838ef2d/href</a></iframe><h3>My pre-cache usage is fine, but how to cache APIs?</h3><blockquote>Yeah PRPL, App-shell model all is in place 😎, but there’s more to offline experience than just blank screens.</blockquote><p>So you’ve made the perfect performant app with 💯score on <a href="https://developers.google.com/web/tools/lighthouse/">lighthouse</a>. Now you want to check the offline experience. preact-cli’s default service worker would have probably cached the app-shells for you. But for the APIs, you’ll need to add <em>runtime strategies</em>. These can be <a href="https://jakearchibald.com/2014/offline-cookbook/#cache-falling-back-to-network">cacheFirst</a><strong> </strong><a href="https://jakearchibald.com/2014/offline-cookbook/#network-falling-back-to-cache">networkFirst</a> <a href="https://jakearchibald.com/2014/offline-cookbook/#cache-only">cacheOnly</a> <a href="https://jakearchibald.com/2014/offline-cookbook/#network-only">networkOnly</a> <a href="https://jakearchibald.com/2014/offline-cookbook/#cache-then-network">fastest</a>.</p><p><strong>Why? </strong>The default caching methodology of preact-cli uses cacheFirst which means service worker looks into the cache for the response and will not go to the server if finds a response in cache(unless anything changed in the pre-cached file and you re-deploy your service worker file). I presume this is what you might not want for your API responses.</p><p><strong>Solution: </strong>You need to add runtime caching strategies for your API calls. This will allow your users to see the freshest content and if they are offline or so, you can then fallback to what was last cached and show it then.</p><p>Imagine a scenario like this: If the user has network, all is good and well. But If the user is offline, he/she can still see my last search results. You can still show the user: last update profile pages/ product pages/ messages etc.</p><p>Here’s what you need to add in your preact.config.js</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d774f5308419583da3a84cf50fca1ca8/href">https://medium.com/media/d774f5308419583da3a84cf50fca1ca8/href</a></iframe><p><strong>P.S.</strong> Doing this(👆) will add sw-toolbox automatically to your service worker.</p><h3>Nups, not convinced. I’ll write one for myself</h3><blockquote>You see service workers are not just about offline experiences, they are way more than that. Reliable performance, offline sync, push notifications and editing your generated service worker isn’t making me happy anymore</blockquote><p>So if you are still not convinced with the approach or you have some corner cases to which you cant seem to cover with our implementation anyhow or even if you have a better setup altogether, then worry not 😃. You can completely opt-out of preact-cli‘s service worker setup altogether.</p><p>All you have to do is build your app with an additional flag.</p><pre>preact build --service-worker false</pre><p>☝️that’s all you need folks. After this, the generated javascript code will no more register the default service worker.</p><p>So you are free to go ahead and implement your own service worker and register it the way you want.</p><p><strong>Note: </strong>This will stop registering the service worker for you but not generating it.</p><p><strong>P.S. </strong>If you’re opting out of the default behavior of the service worker, we’d love to hear your experience and how we can do better. Feel free to open an issue <a href="https://github.com/developit/preact-cli/issues">here</a>.</p><h3>Bonus: Y u still on sw-precache, when u can <a href="https://workboxjs.org/">Workbox</a> 💪</h3><blockquote>There are good chances that you’ve heard of workbox by now and know about its benefits over sw-precache and sw-toolbox.</blockquote><p><strong>Yes, but how? </strong>So you want to start using workbox for its multiple plugins like background-sync / offline-analytics or write one of your owns or may be you want easier integration with custom logic. For using workbox, we’ll again go back to preact.config.js and put <a href="https://workboxjs.org/">workbox</a> instead.</p><p>Here’s the snippet that’ll help you do the same.</p><p><strong>Step 1: </strong>Install preact-cli-workbox-plugin</p><pre>npm i -D preact-cli-workbox-plugin</pre><p><strong>Step2:</strong> Use preact.config.js to generate the sw with workbox instead.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f4afbf5322962a9ce84e4604dd3b6ff9/href">https://medium.com/media/f4afbf5322962a9ce84e4604dd3b6ff9/href</a></iframe><p>That’s all.</p><p>P.S.: You can also use injectManifest functionality where workbox will inject the pre-caching manifest in your custom written service worker. Read more here: <a href="https://github.com/prateekbh/preact-cli-workbox-plugin#injectmanifest">https://github.com/prateekbh/preact-cli-workbox-plugin#injectmanifest</a></p><p>That was me tackling most common service worker related FAQs in preact-cli. please feel free to comment if you’re tackling any other corner case.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e0f034157e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Progressive Web Games Part 3]]></title>
            <link>https://medium.com/@prateekbh/building-progressive-web-games-part-3-31398018580d?source=rss-d5243409b984------2</link>
            <guid isPermaLink="false">https://medium.com/p/31398018580d</guid>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[preact]]></category>
            <category><![CDATA[babylonjs]]></category>
            <category><![CDATA[progressive-web-app]]></category>
            <dc:creator><![CDATA[Prateek Bhatnagar]]></dc:creator>
            <pubDate>Thu, 31 Aug 2017 17:31:01 GMT</pubDate>
            <atom:updated>2017-09-02T06:10:29.385Z</atom:updated>
            <content:encoded><![CDATA[<h4>This is the hardcore part where we’ll take a stage and start creating the game. Lights, camera, shapes, textures, animations and everything begin with this part 👇. Let’s quickly take a deep dive on getting a 60fps game working in super simple javascript code.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6cf50b0w_Iiy4R5sbHfG_w.jpeg" /><figcaption>starting to stitch all our parts together</figcaption></figure><p>Before we begin, just in case you have not read the earlier parts here they are</p><ul><li>Part 1: <a href="https://medium.com/@prateekbh/progressive-web-games-part-1-62dcb89c39ff">https://medium.com/@prateekbh/progressive-web-games-part-1-62dcb89c39ff</a></li><li>Part 2: <a href="https://medium.com/@prateekbh/building-progressive-web-games-part-2-44a0355d6ab8">https://medium.com/@prateekbh/building-progressive-web-games-part-2-44a0355d6ab8</a></li></ul><p>For recap’s sake, this is a game where you swipe to keep a jumping ball on the platforms while the ball moves forward. In order to achieve this, we’ll begin with a simple canvas stretching to the entire screen. This canvas will then be handed over to <a href="https://www.babylonjs.com/">BabylonJs</a> which will do the rest of sorcery.</p><p><strong>Setup:</strong></p><p>In order to get started I have installed <a href="https://www.babylonjs.com/">BabylonJs</a> and <a href="http://www.cannonjs.org/">CannonJs</a> like 👇. Also I’ll be using separate imports from Babylon in order to help it get tree shaken.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/461a64428ff37baa675d94adc4f1c5b1/href">https://medium.com/media/461a64428ff37baa675d94adc4f1c5b1/href</a></iframe><p><strong>Here are the first few basic steps:</strong></p><p>1.) 1st thing we do here is to initiate the game engine and construct a scene. Now imagine this scene to be standing inside a dark black box with nothing besides.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/451a5eb1a245da8b3c5ee8c3e057e40f/href">https://medium.com/media/451a5eb1a245da8b3c5ee8c3e057e40f/href</a></iframe><p>2.) Next, we put lights in this scene so we can see the objects whatever we are putting in this scene. I chose a hemispheric light, which acts up like a lamp in a room and lights up the entire space.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/52f08dec1740061574c1a01cd848e171/href">https://medium.com/media/52f08dec1740061574c1a01cd848e171/href</a></iframe><p>3.) After this ,we’ll need to stand somewhere on the room from where we will watch the game. This is where cameras come in. I am choosing a fixed camera as this game does not allow you to change your viewport but there are other cameras like ArcRotate, FreeCamera etc.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/549ccd4328fe725e7b964695f5d0f5f6/href">https://medium.com/media/549ccd4328fe725e7b964695f5d0f5f6/href</a></iframe><p>4.) Before we go any further we need to start calling `scene.render` in render loop. This is a <a href="https://www.babylonjs.com/">BabylonJs</a> scene is refreshed. Also, think of this as a hook where you can implement something like a “pause” functionality.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/014e740614bebd325dff8332956ec8fa/href">https://medium.com/media/014e740614bebd325dff8332956ec8fa/href</a></iframe><p>5.) We are now good to put a simple object in this empty space, so we begin by putting a sphere in here, which will act like our ball.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f2b9c3cc5eee3a0b493506fa3651794/href">https://medium.com/media/3f2b9c3cc5eee3a0b493506fa3651794/href</a></iframe><p>6.) And after this let’s try creating a simple box under our ball and a put it in simple for loop + a randomized function to layout the initial stage.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/78c248ba6c2d51be6c62d99c8c606ff9/href">https://medium.com/media/78c248ba6c2d51be6c62d99c8c606ff9/href</a></iframe><p>This is how our scene looks right now</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/248/1*ysUjyhDXQ6xpfLGA98mmAA.png" /><figcaption>The scene is set with a sphere and boxes and nothing fancy</figcaption></figure><blockquote>Note: in order for a cleaner code I have broken my game logic into 3 classes. A. The Game scene, B.The Ball, C. The Platform. While all the logic described is the real code, but you just might have to look into one of the three class files.</blockquote><h3>Let there be animations</h3><blockquote>If there’s a game there has to be animation.</blockquote><p>Now there are two type of animations we will do for this game</p><ol><li>Simple key based animations for our objects.</li><li>A tad complex manual frame by frame animation for user input.</li></ol><p><strong>Keyframe based animations: </strong>For a keyframe based animation you just tell the set of keys, which are basically just milestones between 0 to N keyframes and the property which will be affected by these keys. E.g. A bounce animation of the ball will have 2 set of keys, one will control `position.y` and other `position.z` like 👇</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec84176e7af1eef45f7f1e61ce88a954/href">https://medium.com/media/ec84176e7af1eef45f7f1e61ce88a954/href</a></iframe><p>Box’s drop and appear animation is a combination of two set of keys controlling position.y and opacity.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/73cf92e9f3f64482610f67091792e107/href">https://medium.com/media/73cf92e9f3f64482610f67091792e107/href</a></iframe><p><strong>Render cycle animation: </strong>In this method, we put our code in a callback function after which we call the render function of <a href="https://www.babylonjs.com/">BabylonJs</a>. I’ll come back at this later when we’ll start handling user input.</p><p>We’ll use simple animation for our box’s drop and appear animation and our ball’s bounce animation.</p><blockquote>Note: I have placed all the animation keys in a separate animations.js file.</blockquote><h3>Physics OMG 😵:</h3><p>If you would’ve ever thought of creating a game, one of the many horrors that would’ve come to your mind would have been the gigantic amount of work needed to replicate real world physics. E.g. Gravity, Angle of collision, Restitution, Elasticity of collision and so one. Luckily some genius developers already got us covered(I mean we’re still writing jS, do you really think someone wouldn’t have made a library for this already). Enter <a href="http://www.cannonjs.org/">CannonJs</a>, a physics engine which covers multiple shape physics, collision mechanisms, gravity, physics imposters and some more alien tech.</p><p>We’ll use the collision and physics imposter part of this sweet library at our disposal.</p><p>You can think of “physics imposters” to be like invisible objects around your shape which help detect collisions or apply forces on your shapes and objects. And they are super simple to use.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/de0edb68570f654dc80fd192188dccf9/href">https://medium.com/media/de0edb68570f654dc80fd192188dccf9/href</a></iframe><p>Here’s what it means, now we’re able to bounce the ball and detect its collision if it lands on the next platform. Once we detect the collision we just need to restart the ball’s animations and increase our score by one. And if no collision is detected the ball will drop down and we’ll add an event to detect this and tell the user he/she has lost.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd4fd2cc04c2ae1adb00f3a0d61e399a/href">https://medium.com/media/cd4fd2cc04c2ae1adb00f3a0d61e399a/href</a></iframe><h3>User Inputs:</h3><p>As described in the animations section, for user inputs we’ll manually do some animations in our render loop, just before calling this._scene.render(). Our aim here is to make the ball respond to user’s swipe left or right.</p><p>Now BabylonJs follows different dimensions and viewport sizing factor and your pixels won’t really map 1:1 points on the canvas. Hence I decided to take a reference point in the beginning and then factor down the swipeDistance on mouseMove by a certain factor which felt fit for the game.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/95b170eb58f8274b7843a2ec74ffb928/href">https://medium.com/media/95b170eb58f8274b7843a2ec74ffb928/href</a></iframe><p>After this one thing that you can do is that just update the x position of the ball instantly, but this will make the game super duper easy. So rather I made a small piece of code that will add or subtract a small value from the ball’s “x position” and hence maintaining a mid level difficulty.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d55ba93e1e3f59998743bc4bb9961745/href">https://medium.com/media/d55ba93e1e3f59998743bc4bb9961745/href</a></iframe><p>👆with this in place being called in our render loop, we’re good to go with the whole thing.</p><p>Upon intersection I fire a callback to preact code which displays the score on the DOM and upon the lost event fired I fire another callback, to display the re-play fab button.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FvOmqj3_LElc%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DvOmqj3_LElc&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FvOmqj3_LElc%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b3b2aa8290b61036a9bb4eb713d080e/href">https://medium.com/media/8b3b2aa8290b61036a9bb4eb713d080e/href</a></iframe><h3>Trial run:</h3><p>So now I decided to try my game. I landed on the home page and opened the dialog for Guest login, and being a perf freak I started the performance recording in dev tool. When I went to the play route, stood for some time in front of a white screen and then my game stopped. And to my horror, the gigantic loads of BabylonJs &amp; CanonJs did this to my timeline</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ToUqzBPhdKlFubOLoatf1g.png" /><figcaption>a gigantic wait for 6s in the time <a href="https://www.youtube.com/watch?v=3tb-1MWg44Y">when everyone wants everything super quick</a>!!! One word: Unacceptable.</figcaption></figure><p>But not to worry, a super small fix known as prefetch will balance out things for us. so in our head section, I added a &lt;link rel=prefetch.../&gt; which started my download on a low priority and by the time my user checks out the home screen, enters the name or authenticate with Google our bundle would’ve been downloaded. And this would make our timeline happy again 😄</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BXQOiXDpP62iJBFUyIisZA.png" /></figure><p>After you have added a prefetch expect some delta in your initial render time but that’s to balance the overall UX.</p><h3>Note to Service Worker:</h3><p>I am using preact-cli-sw-precache to add runtime caching configuration to preact-cli. With my service worker my aim is to have a minimal pre-cache resources, so that it quickly takes control of the page. Later on whatever resources are requested from the controlled page, our service worker will cache them on runtime with cacheFirst strategy.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d0f6cb71e09bd8b6140cd86229afc2d/href">https://medium.com/media/0d0f6cb71e09bd8b6140cd86229afc2d/href</a></iframe><h3>Conclusion:</h3><p>So we have our game’s start screen up and running ~3.5s and the stage setup(start of web-gl loader) with a delta ~2s. And if the browser has Service Worker all of this drops by several notches from consecutive visits. Also, the user will be able to play this irrespective of network availability.</p><p>We have reached a point where its a full fledged working game with a perfect Lighthouse score.</p><p>If words like analytics and ads do not excite you, this is all the series had it for you. Because there’ll be one last round of changes adding open collective based ads and some analytics.</p><p>Github code: <a href="https://github.com/prateekbh/hopon/tree/part3">https://github.com/prateekbh/hopon/tree/part3</a></p><p>🍻Hope you had good time reading the series.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31398018580d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Progressive Web Games Part 2]]></title>
            <link>https://medium.com/progressive-web-apps/building-progressive-web-games-part-2-44a0355d6ab8?source=rss-d5243409b984------2</link>
            <guid isPermaLink="false">https://medium.com/p/44a0355d6ab8</guid>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[webpack]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[progressive-web-app]]></category>
            <category><![CDATA[preact]]></category>
            <dc:creator><![CDATA[Prateek Bhatnagar]]></dc:creator>
            <pubDate>Mon, 07 Aug 2017 16:45:37 GMT</pubDate>
            <atom:updated>2017-09-01T05:54:30.646Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qwYVJ10p_AqggnKukF63hg.jpeg" /><figcaption>optimizations begin right from the “start screen”</figcaption></figure><h4>Welcome back! In this part we’ll talk about building the login functionality in a way that our app’s Time to interactivity does not take a hit.</h4><blockquote>In the time of “Single Page Applications”, it has become really common and easy for developers to send pieces of javascript code to their user which user might never use. This is why I decided to keep just the login functionality a separate part</blockquote><p>As we discussed in part 1, we will be using <a href="https://firebase.google.com/">Firebase</a> to authenticate our users with Google. In order to start with firebase here‘s the first step</p><pre>// install firebase<br>&gt; npm i -D firebase</pre><p>After firebase is installed, we’ll add it to the <em>home.jsx as shown below 👇</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b9588c7e58804fdfe5d5fff5429c83b9/href">https://medium.com/media/b9588c7e58804fdfe5d5fff5429c83b9/href</a></iframe><blockquote><strong>NOTE: </strong>firebase is distributed in two forms</blockquote><blockquote>a. The entire firebase bundle in one file(app, auth, messaging, database etc)</blockquote><blockquote>b. Every functionality in its own file</blockquote><blockquote>Please do NOT use the first version until you are using all the features. Due to an imperfect tree-shaking, your jS bundle might take a huge hit otherwise.</blockquote><p>Before we go any further here’s a look on how our timeline looks <strong>without</strong> any firebase code</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XHnyGskmAnXF7An3pIOguA.png" /><figcaption>timeline without any firebase code (TTI: ~1.5s)</figcaption></figure><p>Now we’ll try to run our new code(with firebase) as production build. In order to do this run the following two commands:</p><pre>// preact cli tries to prerender the routes for you and firebase<br>// might cause error here, we&#39;ll fix this in next few steps</pre><pre>&gt; preact build --no-prerender</pre><pre>&gt; preact serve</pre><p>You will observe a few things here:</p><ol><li><em>Preact-cli</em> has started warning you about the bundle size, even after using the separate firebase files.</li><li>This has shifted our ‘Time to interactivity’ by 1s 😟. <em>(An entire second looking at a blank screen)</em></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*USG7jxwO-E8mIM73AquPRw.png" /><figcaption>preact cli warning you about sending too much jS in the same bundle.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fJvR5ynWKY8EgNJIUt6xtw.png" /><figcaption>timeline when firebase is also in the route bundle(TTI: ~2.5s)</figcaption></figure><p>☝️this is bad because even though my user wanted to do a guest login he is waiting for scripts which he’ll never use. We’re going to run a perf axe on it. We’re going to use lazy-loading on this and make the rest of the screen interactive without firebase. So people can use features as they become available/interactive instead of clicking on stuff that does nothing.</p><p>In order to do this, we use <a href="https://webpack.js.org/">webpack</a>’s require.ensure and use a <a href="https://prateekbh.github.io/preact-material-components/#/component/linearprogress">LinearProgess</a> to indicate that Google Sign-in is loading in the background.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a14e7409496cfe1be6028143dbec457/href">https://medium.com/media/6a14e7409496cfe1be6028143dbec457/href</a></iframe><p>Here’s what it does for us on the timeline 👇. Notice the ~900ms gain on time to interactivity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xzCJTfhMakOhbTmVTiB0PQ.png" /><figcaption>timeline with lazy-loaded firebase code (TTI ~1.6s)</figcaption></figure><p>What we just did is really important as we’re not blocking our users for anything, stuff is available for users to interact as it gets downloaded.</p><p>We have come to a place where no unnecessary scripts are parsing, a small jS &amp; CSS footprint and one image is download. <strong>Hint: </strong>Here we see some scope of squeezing a &lt;link rel=prefetch tag in order to tell the browser that take X url and start downloading in low priority, we’ll use it in some time.</p><p>So far, a user has landed on our game, quickly got it running, interactive and logged in to play the game. After user has reached here, we’ll route him/her to the main playing screen where a giant(compared to other assets) game engine is waiting to get downloaded so that the game can begin. And if we don’t do a good job at optimizing that, we’re not too far from the slow “<em>download and install”</em> kind of experience of app stores.</p><p>This is what we’ll try to fix in the next part, and I <strong>PROMISE</strong> in next part we’ll do actual game coding as well.</p><p>Our finished up start screen 👇</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/223/1*GyASERJiiHt7Yqq5NIfuMg.png" /><figcaption>login screen</figcaption></figure><p>Code: <a href="https://github.com/prateekbh/hopon/tree/part2">https://github.com/prateekbh/hopon/tree/part2</a></p><p>So stay tuned.</p><p><strong>P.S. </strong>Special thanks to <a href="https://medium.com/u/2d30b2439b4b">Surma</a>, for helping me profile and improve this better.</p><p><strong>Earlier parts: </strong><a href="https://medium.com/@prateekbh/progressive-web-games-part-1-62dcb89c39ff">https://medium.com/@prateekbh/progressive-web-games-part-1-62dcb89c39ff</a></p><p><strong>Next part: </strong><a href="https://medium.com/@prateekbh/building-progressive-web-games-part-3-31398018580d">https://medium.com/@prateekbh/building-progressive-web-games-part-3-31398018580d</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44a0355d6ab8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/progressive-web-apps/building-progressive-web-games-part-2-44a0355d6ab8">Building Progressive Web Games Part 2</a> was originally published in <a href="https://medium.com/progressive-web-apps">Progressive Web Apps</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Progressive Web Games Part 1]]></title>
            <link>https://medium.com/@prateekbh/progressive-web-games-part-1-62dcb89c39ff?source=rss-d5243409b984------2</link>
            <guid isPermaLink="false">https://medium.com/p/62dcb89c39ff</guid>
            <category><![CDATA[progressive-web-app]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[babylonjs]]></category>
            <category><![CDATA[preact]]></category>
            <dc:creator><![CDATA[Prateek Bhatnagar]]></dc:creator>
            <pubDate>Tue, 25 Jul 2017 15:47:36 GMT</pubDate>
            <atom:updated>2017-09-01T05:54:54.395Z</atom:updated>
            <content:encoded><![CDATA[<h4>All app-stores(Google play/iTunes/Windows app store) are filled with tons of games ranging from really simple ones to super complex ones. These games are downloaded millions of times. With the power of PWAs, a lot of these are perfect candidates to be brought to the web instead.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rlzepkpuBE6y6LTSLijYww.png" /><figcaption>Game attack on PWAs</figcaption></figure><p>This is a series where I’ll take up a game called <a href="https://play.google.com/store/apps/details?id=com.ketchapp.hop"><strong>Hop</strong></a> from Google play and try converting it into a Progressive web game, while keeping it at a slick 60 FPS. I’ll also try to cover the following topics while maintaining a perfect 💯 score on lighthouse.</p><ol><li>Animated routing using <a href="https://www.npmjs.com/package/liquid-route">liquid-route</a>.</li><li>Code splitting &amp; Tree shaking to avoid the <a href="https://www.babylonjs.com/">game framework</a> size from hitting our “Time To Interactivity” metric.</li><li>Lazy loading of extra libs to perform additional steps(<a href="https://firebase.google.com/">firebase</a>, <a href="https://www.babylonjs.com/">BabylonJS</a>).</li><li>Progressive offline User experience without burning a hole in User’s network usage.</li><li>Also, try to load ads without hurting any performance metric(but I’ll keep optional unless this <a href="https://twitter.com/_prateekbh/status/881806838253146112">thread</a> works out)</li></ol><blockquote>Disclaimer: I build web apps for living and might make noob mistakes as a game dev, feel free to point them and I’ll fix them for you</blockquote><h3>Step 0: What is the game?</h3><p>It’s a pretty simple game, you tap on the screen and the ball will start bouncing from platform to platform and you would need to swipe to change it’s position on the x-axis to keep it from falling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/225/1*2i2td-Ftk74fIULhuPh6hA.jpeg" /><figcaption>a sample screenshot from original game</figcaption></figure><h3><strong>Step 1: Choosing our guns</strong></h3><p>I will be majorly developing/testing this web app with smartphones in mind(whats the fun if you can’t play on an airplane without n/w). Hence I’ll be choosing <a href="https://preactjs.com/"><strong><em>Preact</em></strong></a> for all of my DOM related jazz and <a href="https://www.babylonjs.com/">BabylonJS</a> for my WebGL related shenanigans.</p><p>Now I can either make this series from a total of ‘n’ to ‘n+2’ parts and configure/explain webpack configurations, plugins and rest of the serving strategy or use the 🔥 ⭐️ <a href="https://github.com/developit/preact-cli"><strong><em>preact-cli</em></strong></a>. Preact-cli will setup a working end to end environment for us to just go and code the application logic. This setup gives us a 3-second headspace for our application code before we hit a bad 5-second mark of interactivity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QaB524JKExOMz7EIXCEZJg.jpeg" /></figure><p>Also, I’ll be using components from <a href="http://npmjs.com/package/preact-material-components"><strong><em>preact-material-components</em></strong></a> to achieve simple UI elements like progress-bar, buttons and more.</p><blockquote>Note: A huge challenge here is to load the gigantic game engine and still not hurt our ‘Time to Interactivity’.</blockquote><h3>Step 2: Getting started</h3><p>Lets do this in super simple steps:</p><pre>// install preact cli<br>npm install -g preact-cli</pre><pre>// create app<br>preact create myGame --dest . --type empty</pre><pre>// add material components<br>npm i -D preact-material-components</pre><pre>// add liquid route<br>npm i -D liquid-route</pre><pre>// add babylonjs<br>npm i -D babylonjs</pre><p>👆this will setup the working directory for you, all you have to do is start building the home screen.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be915061b4f0852d53207377e2be83be/href">https://medium.com/media/be915061b4f0852d53207377e2be83be/href</a></iframe><p>after the above code is in place, it’s just one command to get you started</p><pre>preact serve</pre><h3>Step 3: Next Steps</h3><p>So far we have one dummy screen rendered at home URL, which has our logo and two buttons to get us started with either a <em>“Google login”</em> or a <em>“Guest login”.</em> Next, we will add firebase library &amp; data stores to complete the login step and have the user info before we get started with the main stage construction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*ZDEI4xyqtDZm1vyZJogH5A.png" /><figcaption>dummy login screen to begin with</figcaption></figure><p><em>Code: </em><a href="https://github.com/prateekbh/hopon/tree/part1"><em>https://github.com/prateekbh/hopon/tree/part1</em></a></p><p>See you soon 😃</p><p><strong>Part 2: </strong><a href="https://medium.com/@prateekbh/building-progressive-web-games-part-2-44a0355d6ab8">https://medium.com/@prateekbh/building-progressive-web-games-part-2-44a0355d6ab8</a></p><p><strong>Part 3: </strong><a href="https://medium.com/@prateekbh/building-progressive-web-games-part-3-31398018580d">https://medium.com/@prateekbh/building-progressive-web-games-part-3-31398018580d</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62dcb89c39ff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An effort to make web apps feel better]]></title>
            <link>https://medium.com/@prateekbh/an-effort-to-make-web-apps-feel-better-a29d96f23d61?source=rss-d5243409b984------2</link>
            <guid isPermaLink="false">https://medium.com/p/a29d96f23d61</guid>
            <category><![CDATA[animated-web-design]]></category>
            <category><![CDATA[preact-router]]></category>
            <category><![CDATA[preact]]></category>
            <category><![CDATA[progressive-web-app]]></category>
            <dc:creator><![CDATA[Prateek Bhatnagar]]></dc:creator>
            <pubDate>Thu, 29 Jun 2017 18:11:01 GMT</pubDate>
            <atom:updated>2017-06-30T04:59:38.543Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O4WlBBH-JBkO5WMwc07DYQ.jpeg" /><figcaption>flow better with liquid-route component</figcaption></figure><p>In this time where our web has literally started working without internet, web-apps now load instantly, reside on our devices just next to native apps without any visual discrimination. We certainly have come a long way from conventional mobile web, thanks to Progressive web apps.</p><p>We are capable of playing media with controls/ backdrop on the home-screen of our phone (<a href="https://developers.google.com/web/updates/2017/02/media-session">https://developers.google.com/web/updates/2017/02/media-session</a>), soon enough we may have control to <a href="https://www.w3.org/TR/wake-lock/">Wake lock</a>/ <a href="https://www.w3.org/TR/contacts-manager-api/">Contacts</a> and lot more, but while these will come and make our web apps more powerful. UX is something that we still need to push boundaries for(or may be just uplift our benchmark of what we accept as the average).</p><p>In today’s time when every framework is taking pain to make boilerplates and CLIs for their devs to ease out their setup phase may be its a good time we can focus on stellar experiences. These can be above average right out of the box. The one in spotlight here is <em>Routing;</em> in the age of SPAs we are still majorly doing append/remove kind of routes e.g.</p><ol><li>You click a link</li><li>Everything related to current route is removed from DOM</li><li>New route is rendered</li><li>We accept that this is how it works.</li></ol><p>But this is not a case for a majority of native apps, a lot of very basic common transitions are easy to find in most common apps, is it easier for them to implement, is it better tools..? ¯\_(ツ)_/¯</p><p>Even a for a boilerplate app with react-native its ultra easy to add</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/224/1*viVofZuC4Bw2GaEd024xFQ.gif" /><figcaption><a href="https://facebook.github.io/react-native/releases/0.26/docs/navigator.html#configurescene"><em>https://facebook.github.io/react-native/releases/0.26/docs/navigator.html#configurescene</em></a></figcaption></figure><h3>Sunil Pai on Twitter</h3><p>Web developers, do more animated transitions. Things that blink in and out are no fun.</p><p>Well different communities are trying to get to this, react-router has some form of animations baked, polymer has some components to do the same and in order to achieve something similar.</p><p>And then we have a a parallel universe of #<a href="https://medium.com/u/75a178b86996">Preact</a>(taken care of by its Starlord <a href="https://medium.com/u/30b8f5921914">Jason Miller</a>), where javascript libs is super small. Preact has a <a href="http://npmjs.com/package/preact-router">router</a> of its own, whose awesome API allows you to create extensible route components. One such example is <a href="https://www.npmjs.com/package/preact-async-route"><em>Async Route</em></a> in order to enable you do code splitting and lazy loading.</p><p>But this blog post is about Animated routing, so coming back to it. I kinda always wanted to have something in my router that I can just tell which route to appear how and can just focus on the content of it(<em>blame my react native’s experience</em>). So I started working on something I call “<a href="https://github.com/prateekbh/liquid-route">liquid-route</a>”. The idea is to pass a prop called “<em>animator</em>” to your route which will decide the next route’s entry animation and the current route’s exit animation(yes you read it right, next route will decide the exit animation of the current route). Here’s a sample</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8a6ab04d383a26bcd6f9b38b525541ab/href">https://medium.com/media/8a6ab04d383a26bcd6f9b38b525541ab/href</a></iframe><p>This will sit in and around your exiting code and start animating your routes with the given animations.</p><p><strong>Note:</strong> liquid-route is built with element.animate api hence you might wanna add its <a href="https://github.com/web-animations/web-animations-js">polyfill</a> if you are on a browser which does not support it.</p><p><strong>Don’t want any animation?</strong></p><p>Sometimes you might feel it’s a little too much animation on screen and might not want certain route to animate at all, here’s how you do it without having different ways to declare routes</p><pre>&lt;LiquidRoute path=&quot;/&quot; component={()=&gt;{<br>  return System.import(&#39;./Components/Home/Home.jsx&#39;)<br>  .then(module =&gt; module.default);<br>}}/&gt;</pre><p>👆 notice that the prop “animator” is missing hence there will be no animation to it.</p><p><strong>Demo time:</strong></p><p>Here’s a small peak at what this finally produces</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FhrUMYbQXAvI%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DhrUMYbQXAvI&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FhrUMYbQXAvI%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/14505b62d9fa5a95ef8c8f5fb626dbec/href">https://medium.com/media/14505b62d9fa5a95ef8c8f5fb626dbec/href</a></iframe><p><strong>Perf:</strong></p><p><a href="https://www.npmjs.com/package/liquid-route">liquid-route</a> is based on <a href="https://www.npmjs.com/package/preact-async-route">preact-async-route</a> hence it enables and bring code-splitting out of the box. just the above shown code(<em>getComponent prop</em>) and you are ready to go. For more details refer the <a href="https://www.npmjs.com/package/preact-async-route">preact-async-route</a> package.</p><p>Also while we are at perf, lemme show the devtools timeline of the above demo on my OnePlus One(test on real h/w, remember?).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3DBJ2v6GAdjw0W2izELJDw.png" /><figcaption>no long frames #happy GPUs</figcaption></figure><p><strong>P.S. </strong><a href="https://www.npmjs.com/package/liquid-route">liquid-route</a> under the hood uses <a href="https://www.npmjs.com/package/preact-transition-group">preact-transition-group</a> hence you would need to declare all your routes using liquid-route.</p><p>Hope you guys have a good experience using <a href="https://www.npmjs.com/package/liquid-route">liquid-route</a>. Please feel free to open PRs and issues <a href="https://github.com/prateekbh/liquid-route">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a29d96f23d61" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Super thin material components for your preact app]]></title>
            <link>https://medium.com/@prateekbh/super-thin-material-components-for-your-preact-app-2b7da3e0700c?source=rss-d5243409b984------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b7da3e0700c</guid>
            <category><![CDATA[preact]]></category>
            <category><![CDATA[material-design]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Prateek Bhatnagar]]></dc:creator>
            <pubDate>Wed, 26 Apr 2017 04:30:26 GMT</pubDate>
            <atom:updated>2017-04-26T04:30:26.118Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’ve used a material toolkit before in any of your project, its pretty common that you have run into cases of unnecessary bloat of your final jS/CSS bundle. This mostly happens as most of these package are delivered as a whole and components have dependencies on each other’s piece of code.</p><p>Comes <a href="https://github.com/material-components/material-components-web">material-components-web</a>, this project is specifically aimed to deliver you the components in an a-la-carté fashion, which means each and every component can work independently. Thus meaning that your app’s jS/CSS bundle does not have to take the weight of any un-used components. This results in better load times, time to interactivity etc.</p><p>I built a package that brings this underlying power of these components to the <a href="https://preactjs.com/">preact</a> universe, encapsulating the imperative DOM definitions into declarative preact components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rtgW3tu2Ivv6so-5WmHIHg.png" /><figcaption>i just happened to merge the logo of preact and material design</figcaption></figure><p>In order to use these, install this package</p><pre>npm install preact-material-components</pre><p>After installing, you can import individual components and their styles in your app</p><pre>import Button from &#39;preact-material-components/Button&#39;;<br>import Fab from &#39;preact-material-components/Fab&#39;;<br>import Snackbar from &#39;preact-material-components/Snack&#39;;<br>import &#39;preact-material-components/Button/style.css&#39;;<br>import &#39;preact-material-components/Fab/style.css&#39;;<br>import &#39;preact-material-components/Snackbar/style.css&#39;;</pre><p>☝ The above said approach does works for you if you are using just a couple (2–4) of components from all. While doing this you are probably doing a huge favor to your customers, and the web itself by NOT BLOATING IT.</p><p>While this works great all the time for jS components, the CSS way of doing things might make you sad when you end up using a lot of these components, so when you are using a good number of components from this package, you might wanna explore using one single bundled css file instead. You can take this call by comparing your CSS bundle size by using both of the approach.</p><pre>import &#39;preact-material-components/style.css&#39;</pre><p>Also all of these components adhere strictly to material design specs and preact-material-components does not modify/ skew any functionality provided by them.</p><p>You can go over Docs and Demos <a href="https://prateekbh.github.io/preact-material-components/">on the main website</a>.</p><p>P.S.: preact-material-components do have a easier way to import stuff</p><pre>import {Button, Fab} from &#39;preact-material-components&#39;;</pre><p>BUT none of the tree shaking currently works on removing unused classes, so please DO NOT USE THIS UNTIL YOU USE ALL OF THESE COMPONENTS IN YOUR PROJECT.</p><p>P.S. Want to take a look at sample app? here it is <a href="https://github.com/prateekbh/preact-material-components/tree/gh-pages">https://github.com/prateekbh/preact-material-components/tree/gh-pages</a></p><p>Hope you find these useful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b7da3e0700c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>