Prefetch and better fetching

I was browsing my friend Chris’s new personal website, and couldn’t believe how quick it was when clicking between pages. Inspecting it a bit, I realized that the site makes use of Gatsby’s prefetching, so other pages are actually fetched when you hover their links. This is super smart and makes a ton of sense, but still seems extreme. Then again, modern JavaScript feels like anything goes, so I’m not surprised. As soon as I realized Chris’s site used prefetching, I immediately checked NuxtJS’s features to see if I could enable it, too!

Luckily, NuxtJS did add prefetching in a more recent version, so I was easily able to enable it by upgrading the dependency. The downside is that prefetching is a bit different in NuxtJS. Instead of fetching on hover, NuxtJS uses the Intersection Observer API to prefetch when the link is in the viewport, but it also seems to only load the template—not the content. I could be wrong, especially since I fetch content async from Contentful rather than serving static, but I don’t think I am...

While prefetching in NuxtJS didn’t make a huge difference in terms of speed, I did find another opportunity to make pages load quicker. When upgrading NuxtJS, I also unlocked a new fetch method that lets me asynchronously load data in a non-blocking away. This is super helpful with individual blog posts because, up until this point, I would load both the article as well as the next/previous posts using the asyncData method, which does block rendering until it’s resolved. That means each blog post makes three requests before it can show anything—not great. By using fetch for the next/previous posts, I only need to fetch the post’s content, then the next/previous posts load in after the fact—the way it should be. The cool part about fetch is that it actually does work the same as asyncData when rendering server-side, so the next/previous posts appear along with the content, without a client-side flash.

I don’t know about you, but I think the pages load much quicker now. I’m thrilled! It’s still not as fast as prefetching entire static pages and simply swapping the content, but that’s okay. I’m happy with any progress.