In implementing a fix, I first found where the iframes are rendered, which is this general-use cards component. It's simplified here, but in essence, it loads in card data using a hook, and then for each piece of that data, stored in an array, it would map into this card component, rendering as a child component. And that card component calls to React Twitter Embed, which is a perfectly good popular NPM package that embeds a tweet as an iframe.
That's the standard way to use Twitter's external tweet embedding features, especially since they went all private only or cost-only for their APIs. So, large numbers, dozens, almost 100 iframes all rendering at once. The strategy that I would often take in a situation like this is lazy loading. This is a simplification of the fix we implemented with lazy loading. First, we dot-slice the cards, so that only card 0 through, in this case starting at 6, render at once. Then, every time a card loads, on load, we increment or add a little bit to an extra counter, saying we can additionally load this many more cards. So, after the first few cards load we can keep loading more and more.
Now, 6 is an arbitrary number, but it worked well here because that's roughly the maximum number of iframes anyone would see upon first loading the page. In theory we could have based it on the page's viewport or some such, but I didn't have the time, I was just doing this for fun. And, just confirming, much faster for recording. It's still loading the same number of iframes, it's just waiting to load. It's being lazy in loading all but the first 6. So, yay, that felt nice. And as we'll see in the remaining four investigations, not much React-specific stuff here. But, it is general good web principles. So, a few takeaways. One, unoptimized apps are, in my experience, the most fun to investigate because they might be totally well-crafted, they just haven't had the time to do those low-hanging fruit, those much more straightforward wins for performance. Two, this code was probably totally fine when it was first written. I imagine when the page was first implemented it probably only had 6 or 12 quotes at most, not ideal but not anywhere near nearly 100 iframes. And lastly, lazy loading is awesome, highly recommended as a strategy. If you have a whole bunch of stuff you want to show and only some of it is initially visible to the users, maybe wait to render the rest of it until a second or two. Let's move on.
Hidden embedded images. This was fun. So, I did run a performance score, which is the standard DevTools, hey, how's the performance? within the general Lighthouse family of checks for a page. And it came with a 36 score, which is not ideal, it's in the red. And going down the suggested opportunities for growth, which I'd highly recommend looking into if you ever get a performance score in the red or yellow, the one that first stood out to me was, total size 26 and a half thousand kib, or roughly two dozen megabytes.".
Comments