<?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 Jones on Medium]]></title>
        <description><![CDATA[Stories by Jones on Medium]]></description>
        <link>https://medium.com/@subsecond?source=rss-87fefe57c8e7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*R1IQ9-7vAWidQ4RmE46Uow.jpeg</url>
            <title>Stories by Jones on Medium</title>
            <link>https://medium.com/@subsecond?source=rss-87fefe57c8e7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 01:05:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@subsecond/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[Update Your Codebase to ES2022 .at() With Seven Lines of Code]]></title>
            <link>https://medium.com/@subsecond/update-your-codebase-to-es2022-at-with-seven-lines-of-code-9b777c570597?source=rss-87fefe57c8e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b777c570597</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[refactoring]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[codemod]]></category>
            <dc:creator><![CDATA[Jones]]></dc:creator>
            <pubDate>Fri, 21 Oct 2022 00:26:48 GMT</pubDate>
            <atom:updated>2022-10-21T00:26:48.738Z</atom:updated>
            <content:encoded><![CDATA[<h3>Update Your Codebase to ES2022 .at() With Seven Lines of Code</h3><p>How many times have your written exampleArray[exampleArray.length - 1] in javascript while lamenting that the language doesn’t have <a href="https://www.codingem.com/python-indexing-from-end/">negative indexing</a>? Thanks to ES2022, we finally have an answer to this with .at() for arrays and strings.</p><p>The piece of code above would now be exampleArray.at(-1). So much easier to read. Now that <a href="https://caniuse.com/mdn-javascript_builtins_array_at">all of the major browsers</a> support .at(), it would make sense to start moving over to this new function. It is going to to be annoying to dig through all of our existing code to find and update every instance of .at().</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HMh0AMLytkRNF4cwrGpLqA.png" /><figcaption>Some Jr. dev somewhere is spending hours doing this.</figcaption></figure><p>This is a classic use case of structured code modification, or codemod. A script with all of our source code in plaintext as the input, and freshly modified code as the output.</p><p>Here is that seven lines of code to update to .at(), written using the <a href="https://www.npmjs.com/package/subsecond">subsecond</a> codemod library:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/16617445fdde88f5f6552ee1f1034554/href">https://medium.com/media/16617445fdde88f5f6552ee1f1034554/href</a></iframe><p>Step by step, this is what our code is doing:</p><ol><li>Selecting every MemberExpression (ie. name[index]) throughout all of our code.</li><li>Separate out name and index strings and use them to check if this specific MemberExpression is using the pattern we are looking for.</li><li>Change the text of the expression to the new syntax using the strings we extracted from above.</li></ol><p>Unfortunately, this code isn’t enough on its own. We still need a way to run all of our code through this script, file by file. Also it would be nice to be able to do a dry run and make sure we aren’t breaking anything before allowing a script full write access to every source file in our repository.</p><p>Follow along below for the full setup process (sadly longer than seven lines of code) that allows you to fully utilize the code above.</p><h3>The Full Process</h3><p>We are going to need some boilerplate to run this code modification on our repository. The method that I prefer is a separate codemod directory inside of your project that holds all of the scripts and dependencies.</p><h4>Setup the dependencies</h4><p>In the root of your project, run the following commands to get started:</p><pre>&gt; mkdir codemod<br>&gt; cd codemod<br>&gt; npm init<br>(choose default options)<br>&gt; npm install diff node-dir prettier subsecond<br>&gt; touch index.js</pre><p>Also add&quot;type&quot;: &quot;module&quot; to package.json in order to allow import syntax (This isn’t required but I like it better).</p><p>The packages we are using are:</p><ul><li>diff: To compare changes the codemod makes during dry runs.</li><li>node-dir: Utility to easily find all the right code files recursively.</li><li>prettier: To format the code after it has been modified.</li><li>subsecond: The actual structured code modification library.</li></ul><h4>Add in the Code</h4><p>Now that we have our folder and packages set up, we just need to write a script find every javascript or typescript file in our codebase and apply the codemod to each one.</p><p>In index.js add the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ddd2e742b75c561f2b14e19f4f620d85/href">https://medium.com/media/ddd2e742b75c561f2b14e19f4f620d85/href</a></iframe><p>This piece of code has 3 parts:</p><ol><li>readFiles() recursively looks through TARGET_DIR to find every file with ending with a .ts(x) or .js(x) and puts all the text contents of those files into a single object.</li><li>That single object gets passed to runSubsecond() where we run our code from the top of this article. This is the main part of this script. If you want to write other codemods, just paste the code in here.</li><li>For a dry run we need to do a diffLines() to make sure we’re not breaking anything important. Once everything is checked, we can uncomment writeFileSync() to complete the process.</li></ol><p>I include a prettier format step in this script because structured code modification meant for logical changes, and doesn’t have as much control over spacing changes. A quick run through prettier fixes any slight inconsistencies (ie. .at( - 1) instead of .at(-1)).</p><p>If you don’t use prettier in your project, I would recommend taking this piece of code out, as the diff will only be changes from prettier. Also if you don’t use prettier, I recommend using prettier, automatic code formatting is wonderful.</p><h4>Test run the script</h4><p>After running node index.js inside of the ./codemod directory, you should get a diff output with all of the new .at() functions that will be in your code. It should look like this:</p><pre>- const finalHeight = progressHistory[progressHistory.length - 1];<br>+ const finalHeight = progressHistory.at(-1);</pre><p>It’s really important to make sure that this diff doesn’t have anything weird in it. With codemod, it is really easy to end up having to search for the correct git reset parameters to not lose your repo.</p><h4>Running the script for real this time</h4><p>Now all that is left to do is the actual code modification. Uncomment line 66 from above and do another node index.js to make all of the code changes.</p><p>I recommend doing a git commit before running this command so a git reset can bring you back to a workable state just in case you accidentally break everything (I speak from a lot of experience).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*YgItMwkXHlEUtYgaz1k9Uw.png" /><figcaption>I never get tired of code that writes code</figcaption></figure><p>At this point there is nothing more to do. Congratulations on the successful upgrade to ES2022!</p><p>You also now have a codemod directory set up that can be used for code cleanup, migrations, and refactoring. If you have made it this far, consider clicking the ‘follow’ button to get more software tips and refactoring ideas.</p><h4>In Conclusion</h4><p>I wasn’t being 100% honest with the ‘seven lines of code’ mentioned in the title. There is a lot of extra boilerplate and setup that is required to run structured code modifications across an entire codebase. Once that setup is out of the way though, structured code modification can be pretty powerful.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b777c570597" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Write Your Own Prettier Extensions]]></title>
            <link>https://medium.com/@subsecond/how-to-write-your-own-prettier-extensions-613fe0b75898?source=rss-87fefe57c8e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/613fe0b75898</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[prettier]]></category>
            <category><![CDATA[developer-tools]]></category>
            <dc:creator><![CDATA[Jones]]></dc:creator>
            <pubDate>Tue, 18 Oct 2022 21:44:25 GMT</pubDate>
            <atom:updated>2022-10-18T21:44:25.262Z</atom:updated>
            <content:encoded><![CDATA[<p>Prettier has quickly become one of my favorite tools for writing software.</p><p>For anyone not familiar, prettier is an opinionated code formatting library. It’s claim to fame is the ability to auto-format code while (somewhat controversially) providing very little customization.</p><p>The idea is that there is only one ‘correct’ way of formatting code. This added standardization of formatting makes working with a team of Software Engineers much easier. In software it can be hard to give up personal preferences, but prettier has proven that standardization is much more valuable in the long term.</p><p>The one drawback of prettier is that it draws the line at actual code modification. Prettier will change around your newlines and spaces, but will never make any changes that could affect execution. Because of this, useful things like <a href="https://www.npmjs.com/package/prettier-plugin-import-sort">import sorting</a> need to be done with prettier plugins instead.</p><p>If you prefer to follow along with the full finished repo, here is the finished <a href="https://github.com/jonesnxt/prettier-plugin-jsxattribute-sort">prettier-plugin-jsxattribute-sort</a>.</p><h4>Let’s Get Started!</h4><p>Obviously, you need prettier set up to work with prettier plugins. Pretter’s own documentation has pretty good <a href="https://prettier.io/docs/en/install.html">setup instructions</a> to follow. Before getting started with this guide, make sure you have:</p><ul><li>An existing project you want to add a prettier plugin to with…</li><li>prettier install through npm</li><li>A .prettierrc file</li><li>(optional) VSCode prettier plugin, format on save will change your life.</li></ul><p>Now that all of that is squared away, it’s time to get our folders in order.</p><h4>1: Folder Setup</h4><p>We need a place for our plugin to live. I have opted for putting everything inside of the existing project the plugin is going to be used for. Putting the plugin code within the project works much better for monorepo situations or if your plugin is project-specific. You could also build a plugin as a completely separate repo, but that is more complicated. More information about standalone packages at the end.</p><p>Navigate to your existing project and make a new folder prettier. Then initialize a new npm project and install a few relevent packages.</p><pre>&gt; mkdir prettier-plugin<br>&gt; cd prettier-plugin<br>&gt; npm init<br>(default options...)<br>&gt; npm install prettier subsecond<br>&gt; touch index.js</pre><p>Now you should have a folder in the root of your project prettier-plugin with a npm project set up and index.js ready to go.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/304/1*HyzrzXw2T1FveSrLO8fiqA.png" /><figcaption>Your folder structure should look pretty similar to this.</figcaption></figure><h4>2: Boilerplate code</h4><p>In ./prettier-plugin/index.js add the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/201a7f8321fe7f885b944725f36142ce/href">https://medium.com/media/201a7f8321fe7f885b944725f36142ce/href</a></iframe><p>With this piece of code, we are telling prettier to run our function preprocess() during the preprocess step of prettier being run on typescript and javascript code.</p><p>The preprocess() function gives us a text attribute which is a string containing the raw text of the file, as well as opts which has some metadata about filename and stuff like that. The function returns a string which is the transformed version of the raw file text.</p><p>Inside of preprocess() you can see a few functions working with S, which is <a href="https://github.com/Subsecond-LLC/Subsecond">Subsecond</a>, the structured code modification library. It’s a lot easier to use a library like this as opposed to something like regex or direct AST manipulation.</p><p>Here we are only overwriting the preprocess key of prettier. This is only a small subset of <a href="https://prettier.io/docs/en/plugins.html#developing-plugins">what a prettier plugin can do</a>. You are also able to modify different parser and printer functions and add entirely new languages.</p><h4>3: Prettier Configuration</h4><p>The rest of the setup is pretty simple. Go to your .prettierrc file and add an entry to the plugins array to the path of your new plugin ./prettier-plugin.</p><p>Here’s what it should look like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b3c45f731ca1b792340cbf86b9ec093/href">https://medium.com/media/6b3c45f731ca1b792340cbf86b9ec093/href</a></iframe><p>If you are using .prettierrc.js instead, replace &quot;./prettier-plugin&quot; for require(&quot;./prettier-plugin&quot;) and the rest is the same.</p><p>Once .prettierrc is updated everything should work as intended and you should see your // it&#39;s working! comment show up at the bottom of any file run through prettier.</p><p>You might need to either restart prettier or if you are using VSCode, CTRL + SHIFT + P into Developer: Reload Window to get prettier to correctly recognize the plugin.</p><h4>4: Making the plugin actually useful</h4><p>Right now we have a prettier plugin that adds a comment to the bottom of any file, sort of useless. Luckily, we can pretty easily build something of use.</p><p>For this guide, let’s use a piece of code I wrote to sort JSX Attributes alphabetically. If you are confused as to why you would want to do something like that, I recommend trying it for a few weeks. You don’t have to think about how to logically place attributes anymore and you instantly know where there is a duplicate attribute.</p><p>Replace the TODO comment in index.js with the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/faef34c421a20624db8c683b260ff0c8/href">https://medium.com/media/faef34c421a20624db8c683b260ff0c8/href</a></iframe><p>In this piece of code we select every JSX opening element, then split apart its attributes in groups separated by spread attributes (ie. {...spread}) and sort each group. The extra spread attribute step is important because spreads usually change their meaning based on sort order. Sometimes you want a spread attribute to overwrite a key in the element, sometimes you want the opposite. To avoid this argument, we treat spread attributes like walls and sort everything within their own areas.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/1*-ZB6EfSC_w4WAKA1Ki4MiA.png" /><figcaption>This is a diff of what the plugin does</figcaption></figure><p>At this point we are done. If you’ve been following along but don’t want to go through the steps, I made an npm package <a href="https://www.npmjs.com/package/prettier-plugin-jsxattribute-sort">prettier-plugin-jsxattribute-sort</a> which is basically just the code here plus a readme. Prettier checks all npm packages and auto-installs any package that starts with prettier-plugin-. With an officially published npm package, the steps are essentially the same except you can completely skip step 3.</p><p>You can easily replace this code with some other structured code modification to extend prettier however you like. I would recommend the <a href="https://playground.subsecond.app/">Subsecond Playground</a> to test out different code modifications before dropping them into prettier. Code modification in production very commonly leads to a google search about git reset flags, so it’s nice to test them out somewhere.</p><h4>In Conclusion</h4><p>Going into this project I thought that I was going to have to edit dozens of files and install a bunch of different build dependencies. It turns out that prettier is actually pretty easy to extend. Prettier plugins can get much more complicated when working with printing functions, like this <a href="https://medium.com/@fvictorio/how-to-write-a-plugin-for-prettier-a0d98c845e70">other excellent medium article</a> explains.</p><p>If you’ve made it this far, thank you for reading all of this. I hope you found something valuable. If you end up making a prettier plugin, please send it to me!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=613fe0b75898" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why I’m So Excited About Codemod (It’s AI)]]></title>
            <link>https://medium.com/@subsecond/why-im-so-excited-about-codemod-it-s-ai-a8a38ef48ca4?source=rss-87fefe57c8e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/a8a38ef48ca4</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[github-copilot]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[codemod]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Jones]]></dc:creator>
            <pubDate>Mon, 10 Oct 2022 22:49:19 GMT</pubDate>
            <atom:updated>2022-10-10T22:49:19.530Z</atom:updated>
            <content:encoded><![CDATA[<p>Last week I had my first encounter with an programmer with 100% reliance on <a href="https://github.com/features/copilot">copilot</a>. For those not keeping up with code controversy, Copilot is Github’s AI code generation tool. Just tell the computer what code it should write with human words and it does the rest.</p><p>My friend using copilot ran into the <a href="https://blog.logrocket.com/building-github-copilot-app/">same problems I’ve seen in other posts</a> about using AI code generation. It just <a href="https://www.fast.ai/posts/2021-07-19-copilot.html#code-problems">isn’t that good sometimes</a>. Copilot is relying on any code it can find across the internet, I really wouldn’t expect it to grasp the complexities and best practices of well written software. Instead it commonly suggests old, but frequently used patterns and spaghetti code.</p><p>Not that any of this is new, AI code generation sort of feels like being able to search Stack Overflow without having to switch tabs. The results are also fairly similar to a <a href="https://en.wikipedia.org/wiki/Copy-and-paste_programming">copy-paste codebase</a>.</p><p>I really don’t think this is a bad thing, faster code production and lower barriers for entry are going to bring a lot of cool things to software that didn’t exist before.</p><blockquote>AI code generation sort of feels like being able to search Stack Overflow without having to switch tabs.</blockquote><p>On the other hand code quality is already a huge problem. Engineers already <a href="https://stripe.com/files/reports/the-developer-coefficient.pdf">spend 33% of their time on technical debt</a>. With AI Codegen tilting the scale towards lower code quality it would be nice to have some new tools to balance the scales. Enter Codemod:</p><h3>Well then what is Codemod anyways?</h3><p>Structured code modification or codemod is a way to predictably modify a codebase using a scripting language. Structured because the script has knowledge about the underlying structure of the code itself, instead of Regex which is just string matching.</p><p>For example, here is a codemod written with <a href="https://github.com/Subsecond-LLC/Subsecond">subsecond</a> that replaces a boolean primary attribute on &lt;Button&gt; elements with type=&quot;primary&quot;.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b672fca54a9072e0a698fe6a538deedd/href">https://medium.com/media/b672fca54a9072e0a698fe6a538deedd/href</a></iframe><p>Running this codemod on some sample code gives us this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*eWxQ3RyRhaiR9j24Ns2StQ.png" /><figcaption>Example from <a href="https://playground.subsecond.app/">Subsecond Playground</a></figcaption></figure><p>Notice the multiple other primary identifiers in the code that don’t get in the way of this codemod. This sort of code modification would be non-trivially difficult with regex, or some other unstructured text-based tool. Being able to specifically target code structures like JSXOpeningElement allows for much more fine tuned control.</p><p>With structured code modification, a single change in one file is equivalent to ten thousand changes across hundreds of files. The benefit only comes out once a codebase is large enough that manual fixes would be a pain.</p><p>The first generation of code modification tools (eg. regex, <a href="https://github.com/facebook/jscodeshift">jscodeshift</a>) are incredibly powerful, but remain confusing enough that they only are used at huge scale. I’m excited to see how low the barriers for entry are able to get with the new set of tools (eg. <a href="https://github.com/subsecond-llc/subsecond">subsecond</a>, <a href="https://github.com/coderaiser/putout">putout</a>).</p><h3>Code should be for humans</h3><p>The story of programming languages shows a march towards human readability. Starting with machine code and assembly, either a huge manual or intense memorization was required to have any hope of understanding a piece of code. Now with more modern languages, well written code can start to feel almost conversational.</p><p>The push for easily understood code makes a lot of sense. You should expect each line of code you write to be read and understood by <a href="https://www.goodreads.com/quotes/835238-indeed-the-ratio-of-time-spent-reading-versus-writing-is">at least 10 other people</a> over its lifetime. AI Codegen makes code creation much cheaper, but without code quality, Copilot will waste time in the long run.</p><p>My prediction for the future is that AI Codegen will be used for computer communication and Codemod will be used to bridge the gap between human and computer.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a8a38ef48ca4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Fast Are Shopify Stores?]]></title>
            <link>https://medium.com/@subsecond/how-fast-are-shopify-stores-a929aa091734?source=rss-87fefe57c8e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/a929aa091734</guid>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[real-user-monitoring]]></category>
            <category><![CDATA[web-performance]]></category>
            <category><![CDATA[shopify]]></category>
            <dc:creator><![CDATA[Jones]]></dc:creator>
            <pubDate>Fri, 02 Sep 2022 23:33:14 GMT</pubDate>
            <atom:updated>2022-09-02T23:33:14.843Z</atom:updated>
            <content:encoded><![CDATA[<p>I am the creator of a Shopify real user monitoring tool, <a href="https://apps.shopify.com/subsecond-speed-check">Speed Check</a>. As a result, I have access to a database of around 50,000 Shopify store web performance data points. Relative to the big players that get millions of views a day, this data seems insignificant, but it is certainly enough to do a bit of analysis.</p><p>Please excuse the back of the napkin type presentation for this one. PostgresQL pasted into a spreadsheet remains as my favorite way to do data analysis. It may not be the nicest to look at, but I was able to generate all of these charts in about 20 minutes.</p><h3>Methodology:</h3><p>I used a width_bucket() aggregation in Postgres to seperate the data into 100 different buckets. All of the metrics have a pretty long tail, so I trimmed each to a round number that holds around 90% of the data available. I’ll also state the median and 75th percentile for each. The 75th percentile is what <a href="https://web.dev/chrome-ux-report-pagespeed-insights/">CrUX</a> uses to score websites, so these numbers can be directly compared to those.</p><p>The Y-axis is the count of how many results ended up in each bucket, and the X-axis is in seconds, except for CLS which <a href="https://web.dev/cls/">has its own units</a>.</p><h4>First Contentful Paint:</h4><ul><li>Median: 1.52 seconds</li><li>75th Pertentile: 2.88 seconds</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ppSC-nDF0Nxm9da1Y92V3Q.png" /><figcaption>First Contentful Paint (0–10 sec)</figcaption></figure><h4>Largest Contentful Paint:</h4><ul><li>Median: 2.29 seconds</li><li>75th Percentile: 3.81 seconds</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tsphdJJHFZ8ZlwiM8Ty9pA.png" /><figcaption>Largest Contentful Paint (0–10 sec)</figcaption></figure><h4>Time to First Byte:</h4><ul><li>Median: 0.962 Seconds</li><li>75th Percentile: 1.71 Seconds</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yQXrgFAAMiu0p9geJ0fXvw.png" /><figcaption>]Time to First Byte (0–5 sec)</figcaption></figure><h4>Cumulative Layout Shift:</h4><ul><li>Median: 0.045</li><li>75th Percentile: 0.11</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3a-mCOIa7mEgI9edBWiN8w.png" /><figcaption>Cumulative Layout Shift (0–1 CLS units)</figcaption></figure><h3>Disclaimers and Conclusion</h3><p>These results are from my one little Shopify app, and may not be representative of Shopify as a whole. Ten or a hundred times as much data might make these charts look different.</p><p>Most interesting to me is how high TTFB is in this sample. Google considers a good TTFB to be <a href="https://web.dev/ttfb/">less than 800ms</a>. My results show that only about 40% of page loads were in that zone. I think this is probably due to the difficulty of caching with a server side system like <a href="https://shopify.dev/api/liquid">liquid</a>. Also a lot of the sites using Speed Check are on the less popular side. Cache hit ratio would be lower for these sites than for much larger ones.</p><p>If you want stats like these for your own Shopify store, try out <a href="https://apps.shopify.com/subsecond-speed-check">Speed Check</a>. It’s free and gives you cool data like this to obsess over. I’ll updates these charts every once in a while once more and more data comes in.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a929aa091734" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Real User Monitoring Means for Shopify Sites]]></title>
            <link>https://medium.com/@subsecond/what-real-user-monitoring-means-for-shopify-sites-b02c1af76248?source=rss-87fefe57c8e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/b02c1af76248</guid>
            <category><![CDATA[web-performance]]></category>
            <category><![CDATA[seo]]></category>
            <category><![CDATA[real-user-monitoring]]></category>
            <category><![CDATA[shopify]]></category>
            <category><![CDATA[shopify-development]]></category>
            <dc:creator><![CDATA[Jones]]></dc:creator>
            <pubDate>Fri, 02 Sep 2022 07:27:35 GMT</pubDate>
            <atom:updated>2022-09-02T07:27:35.589Z</atom:updated>
            <content:encoded><![CDATA[<p>The website looks fine to you, but for your customers it’s completely unusable. This is the reoccurring nightmare that I run into whenever I’m working on a website. The goal of Real User Monitoring (RUM) is to help alleviate that nightmare of mine.</p><p>RUM tools work in the background of actual page visits to record load times and errors. Some RUM tools are geared toward the technical crowd like <a href="https://sentry.io/welcome/">Sentry</a>, while other tools aim at a more general audience, like my own <a href="https://apps.shopify.com/subsecond-speed-check">Speed Check</a> Shopify app.</p><p>Shopify uses a RUM tool <a href="https://github.com/akamai/boomerang">Boomerang</a> to gather data about web performance for their internal teams. Boomerang is installed and running by default on Shopify stores, but the Shopify team doesn’t release any of that information to anyone who uses their product. If you want RUM for a Shopify site, you need to look somewhere else.</p><h3>An example from the real world</h3><p>Let’s take a look through one of the Shopify stores that uses <a href="https://apps.shopify.com/subsecond-speed-check">Speed Check</a>: An Italian tire store called <a href="https://pneumaticosuper.com/">Pneumatico Super</a>.</p><p>The store has a fairly typical Shopify setup. A few third party scripts are loaded for analytics and popups, but nothing out of the ordinary for this type of store.</p><p>A typical Shopify store owner would first learn about web performance and page load speed from either Shopify’s online store speed score, or from Google’s <a href="https://pagespeed.web.dev/">Pagespeed Insights</a> score. Both of these metrics rely on the same underlying system, Google’s Lighthouse tool.</p><p>Lighthouse works by loading a webpage in Chrome like normal, and measuring different aspects about how the page loaded. On the plus side it is easily accessible and not hard to explain. On the minus side it only tests for Chrome, and a fully synthetic test (things like caching, location, different navigation types are not taken into account). Probably about 90% of the time that web performance is referenced, Lighthouse is the underlying system that is being used.</p><p>If we run a Lighthouse audit on our example tire store, this is what we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*gDOMMrDr98JhMh3uybfsfw.png" /><figcaption>Pagespeed Insights is really good at making you feel bad.</figcaption></figure><p>At first view, this looks really bad. 38/100 is an F-. This feels like the type of score that a mostly unusable website would get. It is very easy to look at this result and start to blame some of the third party scripts on the page for slowing everything down so much.</p><p>It’s my guess that the people behind Pneumatico Super saw this score, and the subsequent searches for answers led them to Speed Check (and an <a href="https://words.getsubsecond.com/shopifys-image-optimizer-apps-don-t-actually-do-anything-cab901cfd281">ineffective Image Optimizer app</a>). This is what Speed Check tells them for the exact same page, but this time with real users:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*gqVNsxwEF2wlZPLdrFxfqA.png" /><figcaption>Meanwhile for real users, everything seems sort of fine.</figcaption></figure><p>It feels like a night and day difference. From 38/100 with pretty much all red, to mostly all green with a little bit of yellow and red. The underlying numbers for what is considered ‘green’ is the same across Lighthouse and Speed Check. These two results can be directly compared.</p><blockquote>Lighthouse tells you all of the problems you have, RUM tells you which problems are worth fixing.</blockquote><p>So what is going on here?</p><ul><li>It could be a geographical difference. Test server in US vs. real users in Italy could be a big difference if your servers are provisioned in Italy. TTFB has less green than FCP, so I don’t think it’s this one in this case.</li><li>It could be a user base with fast computers. If everyone that visits your website has a 5g connection, web performance is going to be a lot less important than if everyone is on 2g. I don’t think this point has much sway in this case.</li><li>It could be mobile vs desktop. The bigger the computer, the faster its going to be able to make a website show up, (plus a wired or wifi connection helps). I don’t have any evidence to back it up, but my guess is that this is the reason.</li></ul><p>Those are the common differences I have observed, but due to the variance across the whole web, it could be so many different things. This is the true value of real user monitoring. Lighthouse tells you all of the problems you have, RUM tells you which problems are worth fixing.</p><p>It’s also worth mentioning that 80% is not 100%, and there is still a lot of value in giving the best possible experience to that slowest 20% as well. Accessibility is an important aspect of the web, and performance plays an vital role in it.</p><h3>In Conclusion</h3><p>A lot of the time, web performance paints an image of fear and issues. You need to fix these issues now for your website to be usable. Sometimes that just isn’t the case. It is important to remember that the goal of web performance is to give a good experience to the end user. Numbers can help a lot in understanding, but they can also get in the way of the real goal.</p><blockquote>the goal of web performance is to give a good experience to the end user.</blockquote><p>Lots of sites with 100/100 Lighthouse score are fully unusable. On the other hand, many low scoring sites have no real problem, their users are all on desktop with a fast connection. Real user monitoring solutions are a way to solve this problem, and I hope they get more popularity as time goes on.</p><p>If you are interested in trying out RUM, give <a href="https://apps.shopify.com/subsecond-speed-check">Speed Check</a> a try! It’s free and has the cool new metric Interaction to Next Paint (<a href="https://web.dev/inp/">INP</a>).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b02c1af76248" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Shopify’s Image Optimizer Apps Don’t Actually Do Anything]]></title>
            <link>https://medium.com/@subsecond/shopifys-image-optimizer-apps-don-t-actually-do-anything-cab901cfd281?source=rss-87fefe57c8e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/cab901cfd281</guid>
            <category><![CDATA[shopify-apps]]></category>
            <category><![CDATA[image-optimization]]></category>
            <category><![CDATA[web-performance]]></category>
            <category><![CDATA[shopify]]></category>
            <category><![CDATA[shopify-development]]></category>
            <dc:creator><![CDATA[Jones]]></dc:creator>
            <pubDate>Tue, 30 Aug 2022 21:10:41 GMT</pubDate>
            <atom:updated>2022-08-30T21:10:41.231Z</atom:updated>
            <content:encoded><![CDATA[<p>In the web performance world of Shopify apps, image compression apps mostly dominate. There are at least a dozen different options. These services claim to reduce page load times on your website by compressing image files. For a few dollars a month, they will scan through your Shopify account and compress any image file they find.</p><blockquote>The issue is that Shopify is already doing all of this, for everyone, for free.</blockquote><p>The thought process makes sense, take a popular service like <a href="https://tinypng.com/">TinyPNG</a> that compresses image files, and automate it to work with Shopify’s image library system. In many cases, this is a valuable service, many websites pay large amounts a month for an image CDN to do this very thing. The issue is that Shopify is already doing all of this for everyone, for free.</p><p>Shopify has its own internal image CDN that it uses for all Shopify sites called <a href="https://cdn.shopify.com/">Imagery</a>. This is the default option and has access to most recent technology. It serves WEBP and AVIF files to supporting browsers, and supports responsive images. Shopify did a pretty good job with this system.</p><p>As it turns out, Shopify does a better job than these optimization apps themselves.</p><h3>A formal test</h3><p>To prove my point I conducted as impartial of a test as I could: A simple before and after test with a Shopify product image.</p><p>The test image is an <a href="https://unsplash.com/photos/IFlBNNOLHUo">Unsplash image</a> of beautiful Mono County, CA. The original image is uploaded to Shopify, weighing in a <strong>1.6 MB</strong>.</p><p>I tested two different scenarios:</p><ul><li>The thumbnail image of a product: 360px wide</li><li>The fullsized product image: 1100px wide</li></ul><p>These are both fairly standard for Shopify. I don’t think I am giving an advantage to either compressed or uncompressed.</p><h4>The thumbnail test: (360px wide)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*1fN6n9ig-hGL1E4viosnlg.png" /><figcaption>Winner: Default Shopify before compression app</figcaption></figure><h4>The product image test: (1100px wide)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*hLdKoZrYGRnN612x0P2-WA.png" /><figcaption>Winner: Default Shopify before compression app (again)</figcaption></figure><p>I really expected the values to stay the same, but instead of that, the compression apps actually make things worse. My theory is that two rounds of compression using two different strategies causes additional complexity in a file. Just leaving the images alone and using Shopify default uploads seems to be better than relying on one of these services.</p><p>I’m not going to disclose which of the apps I tested with, but from what I have seen all of them operate in pretty much the same way. I have done a few more tests other than this one using a total of 4 different apps on different images and sizes, and none of them are able to change the file size more than a couple percent either way.</p><p>If anyone is able to figure out a flaw in my experimental setup, please let me know. My original guess was these apps would only improve results by like 10%. My findings of often than not resulting in larger effective image sizes is surprising, even to me.</p><h3>Why are people still using these?</h3><p>A lot of these Shopify apps have dozens of positive reviews from customers saying that they saw real improvements.</p><p>Although fake reviews on Shopify’s app store are a rampant problem, (I’ve gotten emails from 3 services trying to sell me reviews), I don’t think that’s the only thing at play here.</p><p>My theory here is <a href="https://developers.google.com/web/tools/lighthouse/variability">Lighthouse variability</a>. Google’s Lighthouse page speed score has been great for introducing more people to web performance metrics. It has it’s problems though. One of the biggest misconceptions for Lighthouse is that the score can vary by up to 20 points on each test. Google themselves recommend using the <a href="https://developers.google.com/web/tools/lighthouse/variability#run_lighthouse_multiple_times">median value of five runs</a> of the test in order to reduce the variability into a useful metric.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UgEZOY0SQXgN7TF0.png" /><figcaption>It’s done us a lot of good, but certainly has its flaws.</figcaption></figure><p>With large variability, people who want to see an improvement will discount the bad numbers from Lighthouse and keep the good ones. I know I am guilty of doing this when working on web performance. If you want something to work, its easy to trick yourself into thinking that it does.</p><p>If you want to see how fast your shop actually loads for real users, consider trying out <a href="https://apps.shopify.com/subsecond-speed-check">Subsecond: Speed Check</a>. Real user monitoring avoids a lot of the problems of Lighthouse, plus it’s really cool.</p><h3>In conclusion</h3><p>I recommend that you don’t pay money for Shopify image compression apps. It’s crazy to me that so many people are paying monthly for a service that gives them no benefit.</p><p>In general, web performance continues to have some legitimacy problems. I think it mostly stems from a knowledge gap between very technical engineers, and the people actually running ecommerce stores. A push towards defined metrics seems to be helping a lot. Hopefully, improvement will continue into the next few years, and we will see less situations like this one.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cab901cfd281" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Is Shopify’s Checkout Page So Slow?]]></title>
            <link>https://medium.com/@subsecond/why-is-shopifys-checkout-page-so-slow-9f5880c85e91?source=rss-87fefe57c8e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f5880c85e91</guid>
            <category><![CDATA[shopify]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[shopify-apps]]></category>
            <category><![CDATA[web-performance]]></category>
            <category><![CDATA[shopify-development]]></category>
            <dc:creator><![CDATA[Jones]]></dc:creator>
            <pubDate>Mon, 29 Aug 2022 23:01:50 GMT</pubDate>
            <atom:updated>2022-08-29T23:01:50.990Z</atom:updated>
            <content:encoded><![CDATA[<p>Anyone who has spent time working with Shopify has probably run into this problem. You click the ‘Checkout’ button and there is at least a 3 second delay before the Checkout page actually shows up.</p><p>There are a large number of threads on Shopify’s help forum about this problem and basically all of them are answered with typical web performance stuff. Your images are too big, or you have too many apps installed.</p><blockquote>As it turns out, it’s none of those common issues.</blockquote><p>I recently ran into this a slow Checkout page and spent hours getting to the bottom of the problem. As it turns out, it’s none of those common issues. The problem with the Checkout page has to do with how Shopify works internally.</p><p>Shopify waits until the ‘Checkout’ button is pressed to <em>start</em> creating the checkout page. Instead of only downloading a page, we have to wait for the checkout page to be created as well. Both these tasks take at least a second, so an inescapable two second delay is added on to any other performance problem the page might have.</p><blockquote>Shopify doesn’t create the checkout page ahead of time.</blockquote><p>All other pages on a Shopify website have been generated by Shopify ahead of time. All of the code for the homepage and product pages is just waiting around to be sent to you right when you ask for it. The checkout page is the odd one out. Creating a page on the fly, then giving to the user is much slower.</p><h3>What is the solution?</h3><p>The forum posts I’ve found ‘solving’ this problem end up missing the core issue at play. As a result, the common recommendations are usual web performance fixes like use less third party scripts and manage images correctly. This is still good advice, but misses the point.</p><p>I spent a long while searching for a way to get around the underlying slowness of the checkout page, but I wasn’t able to find anything. After a long while of <a href="https://words.getsubsecond.com/shopify-app-development-is-sort-of-a-disaster-53deef5c397f">figuring out Shopify apps</a>, I made the solution myself. <a href="https://apps.shopify.com/prefetch-checkout">Prefetch Checkout</a> is now available and free for everyone who wants to fix this problem on their store.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dH0M5RNgsy1Kk_XTLP6t1w.png" /><figcaption>It’s literally the only way to fix this problem.</figcaption></figure><p><a href="https://apps.shopify.com/prefetch-checkout">Prefetch Checkout</a> generates the checkout page ahead of time and stores it in the browser until its needed. The process is very similar to the very popular <a href="https://instant.page/">instant.page</a> script. Grabbing a resource before it is needed is always going to be faster than waiting until the last second.</p><p>The app itself only inserts a <a href="https://gist.github.com/jonesnxt/b6178b2fb8aef5336c9a3731c9f757f9">single small JavaScript file</a> into your Shopify store that makes these changes. The code is injected directly into the page, so no waiting for a third party server is necessary.</p><h3>Why is it like this?</h3><p>The checkout page loading problem stems from one of the core problems Shopify has. The Shopify platform was created over fifteen years ago. Some core methods and technologies have become outdated over its lifetime. The most obvious outdated technique is also the cause of our problem today: over-reliance on 302 redirects.</p><blockquote>You got close, but you should actually be looking somewhere else.</blockquote><p>302 is the status code for a Temporary Redirect. It is basically a website’s way of telling you that you got close, but you should actually be looking somewhere else. The server doesn’t return any of the content you asked for, but it does give you a URL that probably will have that content.</p><p>Specifically in the checkout page case, /checkout is requested, and a 302 redirect is returned with the address to a /checkouts/[id] link which is the location of the actual checkout page.</p><p>Shopify uses more 302 Temporary Redirects than any system I’ve seen in the last five years. I’ve even seen a case with three 302 redirects in a row.</p><p>This method isn’t ideal because of the unnecessary back and forth between the user and server. Each time a computer asks a website something and get a response, data needs to travel from one location to another. Doing this twice will just take twice as long.</p><blockquote>302 Redirects are unnecessary and twice as slow.</blockquote><p>Before single page web apps and the <a href="https://developer.mozilla.org/en-US/docs/Web/API/History_API">History API</a>, using 302 Temporary Redirects would have made much more sense. With modern web technologies, this method is easily fixable and two times slower.</p><p>I hope Shopify fixes the underlying problem and moves away from 302 Redirects. No matter if you are paying $1 /month for the cheapest plan, or $2000/month or more for Shopify Plus, the checkout page will take at least two extra seconds to load than it needs to.</p><p>Until then feel free to use <a href="https://apps.shopify.com/prefetch-checkout">Prefetch Checkout</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*5saRnDvaBd6gmHBUeaEjJQ.png" /><figcaption>Not the most creative thumbnail I’ve created, but it gets the point across.</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f5880c85e91" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Should You Capitalize the T in nullthrows?]]></title>
            <link>https://medium.com/@subsecond/should-you-capitalize-the-t-in-nullthrows-96d5e39ded86?source=rss-87fefe57c8e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/96d5e39ded86</guid>
            <category><![CDATA[code]]></category>
            <category><![CDATA[npm]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Jones]]></dc:creator>
            <pubDate>Sun, 28 Aug 2022 18:57:16 GMT</pubDate>
            <atom:updated>2022-08-28T18:57:16.336Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://www.npmjs.com/package/nullthrows">nullthrows</a> is a npm package that is probably familiar to anyone that has spent a while in the TypeScript world. It is a simple utility that throws an error if a value is null, otherwise it asserts that the value is not null.</p><p>The entire library is basically just the code below, but with some extra type information.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/98fa46bb575ec08d84fd9583d0f1c76d/href">https://medium.com/media/98fa46bb575ec08d84fd9583d0f1c76d/href</a></iframe><p>In situations like graphQL responses with a lot of potential nulls, nullthrows is really useful for making VS Code less mad at you.</p><h3>So What’s the Problem?</h3><p>Put simply: camelCase. And autocomplete.</p><p>Javascript naming conventions are fairly well defined at this point. Basically all of the code I’ve worked with recently follows the basic naming rules:</p><ul><li>Variables and functions are camelCase</li><li>Constants are ALL_CAPS</li><li>Class names and JSX Objects are <a href="https://stackoverflow.com/questions/60244301/where-does-the-word-pascal-case-come-from">PascalCase</a></li></ul><p>So the problem is, nullthrows is a function, but the ‘t’ is not capitalized.</p><p>This probably seems fairly insignificant, especially to anyone who doesn’t work on software, and for the most part it really isn’t. There is no great benefit to a capital ‘T’ aside from fixing a slight personal annoyance.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e3f6de8dfd33afd44ebee0e764cc86b6/href">https://medium.com/media/e3f6de8dfd33afd44ebee0e764cc86b6/href</a></iframe><h3>Towards a Solution</h3><p>Now some of you are probably thinking: “It’s a default import, just rename it nullThrows when you import the package.”</p><p>This is my usual solution to the problem. It works for me, but on larger software teams I’m fighting against the tide of autocomplete.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/553/1*7AyKhg_IFXJnv55cpJqEHQ.png" /><figcaption>If VS Code autocomplete jumped off a bridge, I would jump too.</figcaption></figure><p>If VS Code autocompletes and autoimports nullthrows with a lowercase ‘t’, who is going to remember to rename the import and all uses every time? The answer I’ve found is basically no one, not even me some of the time.</p><p>In my opinion, inconsistency between the capitalized and lowercase version is worse than just using the lowercase ‘t’. Trying to rename the default import for everyone, everywhere is a losing battle. A better strategy is to attack at the source of the problem.</p><h3>A New Way Forward</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*AKE1ifNAKbADbfx7mFnUBg.png" /><figcaption>It seems like I’ve spent too much time on this but I still think it’s worth it.</figcaption></figure><p>I present: <a href="https://www.npmjs.com/package/capital-t-null-throws">capital-t-null-throws</a>, a brand new, exciting npm package. I took the original package and did a bunch of renaming. With this package, the autocomplete and autoimport in VS Code default to nullThrows.</p><p>If anyone actually cares about this as much as I do, you are welcome to use <a href="https://www.npmjs.com/package/capital-t-null-throws">capital-t-null-throws</a>. I will continue to maintain it (though I doubt it needs much maintenance) until the end of time. If anyone manages to switch an entire organization to this library from nullthrows, I will buy you a beer.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96d5e39ded86" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Multi-Armed Bandit of Startup Decision Making]]></title>
            <link>https://medium.com/@subsecond/the-multi-armed-bandit-of-startup-decision-making-1fca1e356dd3?source=rss-87fefe57c8e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/1fca1e356dd3</guid>
            <category><![CDATA[multi-armed-bandit]]></category>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[statistics]]></category>
            <dc:creator><![CDATA[Jones]]></dc:creator>
            <pubDate>Wed, 24 Aug 2022 03:20:47 GMT</pubDate>
            <atom:updated>2022-08-24T03:20:47.185Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1GUdjJh4u9bepofI" /><figcaption>Which slot machine will you choose?</figcaption></figure><p>You find yourself on the floor of a dusty, old timey casino holding a $100 bill. Spread out in a long row in front of you are twenty slot machines. All of these machines have a different house edge. In the long run, some will take your money, while others will give you a nice return. From where you stand, all of the machines look identical.</p><h4>How do you discover the best machine without going broke?</h4><p>This thought problem is called the Multi-armed bandit problem. Ever since I started a company, I think about it constantly. At any one time I could be doing dozens of things. Deciding what to focus on has quickly become one of my hardest challenges.</p><p>The multi-armed bandit problem is most commonly used for A/B testing in advertising. We don’t know which ad will perform well until we try, but how long should we use an under-performing ad until we get rid of it?</p><p>I’m a <a href="https://www.linkedin.com/pulse/box-puzzle-i-have-been-thinking-years-alex-jones/">well documented Math nerd</a>, so I tend to apply math thought problems to my everyday life. Most of the time there is not much return from thinking about merging lanes as a calculus problem or using Fermi estimation to decide how much pasta to make. In the case of business decision making though, the multi-armed bandit problem seems to have some definite benefits.</p><p>In an attempt to convince you that this way of thinking is valuable, let’s start with the problem itself, then how I apply it while working on <a href="https://www.getsubsecond.com/">Subsecond</a>.</p><h3>What is the solution?</h3><p>As with many math thought problems, basically all of the buzzword worthy strategies can be used as a solution. You can use Markov chains, neural networks, reinforcement learning algorithms, Monte Carlo simulations and more. A lot of those options are really cool and have varying degrees of success, but I prefer a method called Thompson sampling. It feels very intuitive and helpful while avoiding a lot of extra math. (but, <a href="https://web.stanford.edu/~bvr/pubs/TS_Tutorial.pdf">there is math if you want it</a>)</p><blockquote>Use each slot machine proportionally to the likelihood that slot machine is the best.</blockquote><p>If you estimate a slot machine has a 50% chance to be the highest returning machine, use that machine 50% of the time. Every so often adjust your probability estimates with new information you have gathered.</p><p>I am sweeping under the rug any explanation about how to calculate those probabilities, and how to adjust them given new data (<a href="https://www.3blue1brown.com/lessons/bayes-theorem">Bayes’ theorem</a> still makes my brain hurt).</p><p>Even without heavy math, this strategy in allows you to eventually converge on a single best machine, so long as your estimates are reasonable.</p><p>From here you can probably see how Thompson sampling can be used out there in the real world.</p><h3>What has it gotten me?</h3><p>The biggest I’ve gotten from this endeavor is learning when to stop writing code and start selling. The classic engineer founder dilemma: How much code is enough? (Or I guess most of the time: “Please stop writing code, here is why”).</p><p>Under the Thompson sampling model, I should start working on sales when the probability that sales is the most important thing to be doing is nonzero.</p><p>This result is pretty embarrassing to me as I would probably say sales has around a 60% chance of being the most important thing for Subsecond at the moment and I have not been devoting anywhere near 60% of my time to it.</p><p>I’ve found analyzing current priorities, and comparing to where time is actually going to be fairly illuminating:</p><ul><li>Sales/Marketing — Chance of most importance: 60% | actual time spent: 30%</li><li>Engineering — Chance of most importance: 15% | actual time spent: 60%</li><li>Updating website copy — Chance of most importance: 25% | actual time spent: 0%</li><li>Convincing people I’m cool on Medium — Chance of most importance: 0% | actual time spent: 10%</li></ul><p>So I’m doing pretty bad currently. Fitting with the stereotypical Eng founder, I am undervaluing sales work and overvaluing engineering work.</p><p>Maybe some day I will learn.</p><p>Hopefully this is an helpful framework for you to try out, or at least a new prospective on an age old problem. Let me know what you think, and data scientists please tell me what I got wrong and what algorithms I should be using. (<a href="https://towardsdatascience.com/the-upper-confidence-bound-ucb-bandit-algorithm-c05c2bf4c13f">UCB</a> just doesn’t seem as cool to me)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1fca1e356dd3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Device Pixel Ratio is Breaking Your Srcset]]></title>
            <link>https://medium.com/@subsecond/device-pixel-ratio-is-breaking-your-srcset-f650f1a548e3?source=rss-87fefe57c8e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/f650f1a548e3</guid>
            <category><![CDATA[web-performance]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Jones]]></dc:creator>
            <pubDate>Wed, 10 Aug 2022 22:14:33 GMT</pubDate>
            <atom:updated>2022-08-10T22:14:33.033Z</atom:updated>
            <content:encoded><![CDATA[<h4>Device pixel ratio causes a bunch of problems, then just doesn’t tell you about it.</h4><p>The srcset property on &lt;img&gt; tags is great. It cleanly solves a fairly difficult problem. Different sized images for different viewport sizes without JavaScript would have been unthinkable a few years ago. The only problem is that complexity is inevitable when dealing with the web. A large number of websites think they are benefiting from srcset, but are actually not in many cases.</p><p>Take a look at this example, <a href="https://backlinko.com/">backlinko.com</a>. I just happened to have the page open and it makes my case. (there is still comedy in linking back to a backlinking service).</p><p>It’s a Next.js site, as a result it’s optimized better than the vast majority of the Internet. (<a href="https://nextjs.org/">Next.js</a> is great). The site has a preload link with the<a href="https://www.stefanjudis.com/today-i-learned/how-to-preload-responsive-images-with-imagesizes-and-imagesrcset/#preload-responsive-images-with-%60rel%3D%22preload%22%60">imagesrcsizes</a> property with a corresponding srcset for the LCP image. Textbook web performance stuff. They certainly have been reading web.dev articles.</p><p>Despite all of this lighthouse still flags image size as incorrect.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*mlFkzVYjkdgJUuc_OxCdbQ.png" /><figcaption>next/image is being used here, but it isn’t working as intended.</figcaption></figure><p>And lighthouse is correct, the image is <strong>five times larger</strong> than it needs to be.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/1*oDe5l2e6OCKvh2tiQQs4Fg.png" /><figcaption>A bit overkill to use an 800px wide image for a 162px box</figcaption></figure><p>So what is going on here? Why is the best performance framework making an obvious performance error?</p><h3>Device Pixel Ratio</h3><p>In 2010, Apple unveiled its new <a href="https://en.wikipedia.org/wiki/Retina_display">Retina Display</a> technology. In order to make text and images look nicer, Apple doubled (and eventually tripled) the number of pixels* per inch on their devices. This ended up being pretty cool, although above a certain point, humans <a href="https://observablehq.com/@eeeps/visual-acuity-and-device-pixel-ratio">don’t get any benefit</a> from this. (I highly recommend <a href="https://observablehq.com/@eeeps/visual-acuity-and-device-pixel-ratio">Eric Portis’ paper</a> on the subject).</p><p>Apple made its OS and all of its apps compliant with the new system, but there was one more problem: Websites have been designed 96ppi desktop screens for decades at this point. The <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Viewport_meta_tag">viewport meta tag</a> took a while to make its way into browsers and most websites looked like this on mobile for a few years:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/369/1*4vYKHO1VkaIXpC2eymIkcQ.png" /><figcaption>The good old days of <a href="https://developer.chrome.com/blog/300ms-tap-delay-gone-away/">waiting 300ms</a> for a click event.</figcaption></figure><p>Most people weren’t happy with a 4 inch wide screen displaying 1000 pixels of unreadable text, then having to zoom and pan across each line of text to read. Something had to be done, and the answer was to make pixels on the web different than pixels in a display.</p><p>*As defined by W3C, a pixel is <a href="https://drafts.csswg.org/css-values/#absolute-lengths">1/96 of an inch</a>. Web pixels are an absolute length and therefore can’t have a per inch density other than 96ppi.</p><p>So browsers basically just said, don’t worry about it, pixel density is our problem, we’ll figure it out for you. Browsers began to translate code written for 96ppi screens into whatever density the screen was actually using. The browser rendered full resolution images and text where it could.</p><p>Browsers take pixel density into account when deciding on which srcset image to pick. If a screen has a 3x density, the browser picks an image that is triple the size to fit all of those extra pixels.</p><h3>So then what’s the problem?</h3><p>All of this seems fine. Screens with higher density want to use that density with higher definition images. With the current strategy this is easily achieved.</p><p>The problem is that the average person only benefits from 1.25x standard resolution. Phones these days are reaching into the 3x to 4x territory.</p><figure><img alt="1.25x resolution is all that is needed for 20/20 vision." src="https://cdn-images-1.medium.com/max/657/1*pqR5k7PaY-QpljK_yvkrJw.png" /><figcaption>After 1.25x, there is only a difference if you press your face to the screen.</figcaption></figure><p>Unless all of your users have spectacular eyesight, a lot of bytes are going to be wasted sending a higher definition image than what is realistically noticeable. this problem is polynomially bad as images are two dimensional; an image with 3 times with width and height will have a 9 times bigger file size. (slightly less because image compression but still).</p><p>Given this information, I don’t know why phones go above 2x pixel density. Is it just a marketing thing? Does it help for video somehow? Are we still doing that thing where you put your phone on your face for VR? If you have any information on why this is, please let me know. I’ve been trying to figure out why why part of this for like a month but haven’t gotten anywhere.</p><h3>Is there a way to fix this?</h3><p>Sort of. It’s pretty ugly. But also kind of beautiful.</p><p>We can rely on using a lower quality level on our images on screens with higher pixel density. Given how I understand image compression to work, I think this brings us to about even, size and quality wise. (Something about Fourier maybe).</p><p>I remember thinking of this fix on my own, but upon research I may have just stolen the idea from <a href="https://jakearchibald.com/2021/serving-sharp-images-to-high-density-screens/">Jake Archibald’s blog</a>, (his article is probably better than mine too).</p><p>Say what you want about prefixing, but -webkit-min-device-pixel-ratio has <a href="https://caniuse.com/mdn-css_at-rules_media_-webkit-device-pixel-ratio">near universal support</a>. No other method is as cross browser as this one, though its ugly.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b7c01fe5d9ee2dd91369c88f516d5330/href">https://medium.com/media/b7c01fe5d9ee2dd91369c88f516d5330/href</a></iframe><p>This solution relies on steering into the skid of the browser selecting a larger image on higher dpr screens, and instead just downgrades the quality of the image by using lossy compression.</p><p>No matter the device pixel ratio, images are about the same file size, finally fixing our original performance problem.</p><figure><img alt="Images properly sized. Success." src="https://cdn-images-1.medium.com/max/647/1*7CKUvpyvQ_Yt5aB5HEYaUA.png" /><figcaption>Success, but at what cost?</figcaption></figure><h3>How do we fix this?</h3><p>I’ve been thinking about what my recommendation to the standards people would be about how to make something like this take less than 60 lines of code to accomplish.</p><p>I think I would put my money behind the <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/image-resolution">image-resolution CSS property</a>. Things would still be confusing, but at least developers would be able to fully control how their images are displayed, instead of having to rely on weird hacks.</p><p>Also lighthouse should probably have a warning about this that points to an article somewhere. Having an error message tell you to do something that you have already done is one of the most frustrating experiences a Software Engineer can have.</p><p>It took me weeks to figure out that this problem was happening to my production code and another week after that to figure out how to fix it. Hopefully we can save some other people’s time in the future and make this quirk of image loading more widely known.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*-uX-Kwlp7KeDlQ1i9HpOKQ.png" /><figcaption>I think that is sufficient as a thumbnail.</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f650f1a548e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>