Improve Nuxt TTFB

I’ve recently had to go through this process with a rather large Nuxt application, so I can share some of the insights and solutions we came up with. We managed to bump ours up by about 40 points before we were happy.

My number one piece of advice for anyone reading: Ditch the frameworks. By design, they are bloated to handle as many common use cases as possible and make application as easy as possible, at the expense of size. In the realm of browsers, where size and speed are everything, each new framework (Nuxt, Vue, Vuetify) adds another layer of abstraction that negatively impacts size and speed.

Anyways, with that out of the way, here’s some other pieces of advice for those that cannot ditch the frameworks.

Lighthouse can often be misleading

We found that the “Remove unused Javascript” warnings were basically impossible to fix with Vue. The problem is that Lighthouse is only able to inspect the code that is actually run during the test, and has no idea that code for error handling or onclick handling in the Vue runtime is necessary, until of course it is.

Unfortunately, it’s not possible to know ahead of time what code in the runtime is going to be necessary, so it all needs to be sent. However, as the developer, you at least have control over what 3rd party libraries, modules, and plugins are needed during the initial load of the application. It’s up to you to ensure only the necessary pieces are sent and used.

So in Lighthouses eyes, there’s lots of useless, unused code. However, the second the application needs to do anything, it’s no longer useless. Hence why it is somewhat misleading.

Always keep this in mind, because there’s a lot of “problems” that these tools will report that are just a fact of how Javascript applications work. To me, it seems that the developers of these frameworks still have a few more hurdles to overcome in making Javascript apps truly accessible and performant in the eyes of Google.

Keep your Plugins and modules short.

Each plugin you add to your application in the nuxt.config.js increases the size of the main JS bundle included in each page. This inevitably leads to lots of unused code, huge JS file sizes, and of course, longer load times.

It’s perfectly valid to instead add plugins to only the pages they’re needed on:

// inside the SocialSharing.vue component
import Vue from 'vue'
import VueGoodshare from 'vue-goodshare'

export default { ... }

A reminder though: The page this import happens will still have all the code from vue-goodshare added. It’s much better to instead only include the components from these libraries that you actually need.

A good way to check this is running your build with the analyze property set to true. (It may be helpful for you to share your analysis here)

Reduce Initial Server Response Time

If you’re already running the best server, there’s still a few things you can do to help speed things up.

  1. Leverage caching for your pages, so that there’s no need to render them server side. However, some of these tests (like Lighthouse) specifically disable caching, leading to poor results.
  2. Reduce the amount of work required to render pages. Ensure there’s no blocking API calls happening, keep pages simple and small, and ensure that the server is not overloaded.
  3. Utilize edge caching, or edge deployments, so that your application is closer to your users. For example, if your application is deployed in USWEST, and Lighthouse is being tested in Dubai, you’re likely going to see a lot of latency in that request, which will drive up the server response time.

You may need to follow this up with the specific server you’re running, and where it’s located to get more help. However, the points I outlined would almost certainly get your TFFB to a green score.

Minimize Main Thread Work

In browsers, the main thread is where all the action happens. It is solely responsible for handling user interactions, updating the page, and in essence, turning a document of HTML into a living application. A main thread that is too busy can lead to performance problems, especially noticeable by users when they’re trying to interact with your page.

Often, when seeing this, it’s because you’re running too much Javascript. Specifically, you’re running too much Javascript all at once, which ends up blocking up the main thread. Javascript-heavy applications are notorious for this, and it can be a really challenging problem to solve.

The single biggest helper for our app was delaying the loading of unimportant scripts. For example, we run Rollbar, and Google Analytics on all our pages. Instead of loading the scripts at app-start, we instead just load their small command queues, and delay the load time of the big scripts by ~5s. This frees up the main thread to focus on more important things, like rehydrating the Vue application.

You’ll also find significant savings by just reducing the amount of JS there is to process. Each line of code returned to the client is another line that has to be sent, parsed, and executed. I would definitely take a look at your modules and plugins first to see if there’s some low hanging fruit.

Reduce Javascript Execution Time

This is another unfortunate metric being used, which in our test often just means “the app is still doing something”. I say it’s unfortunate because in our experience it did not impact the performance or user experience in the application.

We frequently saw our third party services, like Intercom, Rollbar, GA, etc, extending their execution times well past 10s, and with third party code, there’s nothing you can do besides not use it.

My advice: Focus on optimizing the application using everything else I’ve highlighted. This is something that can be incredibly difficult to specifically fix, and is usually just a symptom of other things, such as the main thread being too busy, third part code being slow.

One Last Piece Of Advice

If all else fails, you may be able to “trick” some of the tests in your favour. We did this by delaying the load of our GA and Rollbar scripts until after the test has completed. Remember, this tool is looking at certain metrics in a certain timeframe, and scoring you based on that. You may be able to leverage simple alternate techniques, like lazy loading below the fold, to see a noticeable difference in performance.

Anyways, this is quite a complicated task, and by no means is there a “3 step guide to success” here. You’ll find plenty of guides online claiming they’ve brought their Vue app from 30 to 100 with a few simple changes, but they all ignore the fact that real apps have a lot of code and do a lot of things, and balancing that with speed and performance is an art form.

You may want to take a look at resources such as the shell application model, or service workers.

If you need any clarification on this post, feel free to ask away. But keep in mind, the question you’re asking is broad, and doesn’t just have a single “right” way of approaching. It’s ultimately up to you to take the important bits here and apply them as you can.

Update with examples

Most of what I’ve talked about has been quite hard to show examples for, as I’ve covered topics that are either overly simplistic and don’t need an explanation, or are vague concepts to begin with. However, one method we used that had some good results can be shown.

Here’s an example of a modified script we use to load Intercom:

    var APP_ID = "your_app_id_here";
    window.intercomSettings = {
        app_id: APP_ID,
        hide_default_launcher: !0,
        session_duration: 36e5
    function() {
        var n,
            t = window,
            o = t.Intercom;
        "function" == typeof o ? (o("reattach_activator"), o("update", t.intercomSettings)) : (n = document, (e = function() {
        }).q = [], e.c = function(t) {
        }, t.Intercom = e, o = function() {

            // Don't load the full Intercom script until after 10s
            setTimeout(function() {
                var t = n.createElement("script");
                t.type = "text/javascript",
                t.crossorigin = "anonymous",
                t.async = !0,
                t.src = "" + APP_ID;
                var e = n.getElementsByTagName("script")[0];
                e.parentNode.insertBefore(t, e)
            }, 1e4)

        }, "complete" === document.readyState ? o() : t.attachEvent ? t.attachEvent("onload", o) : t.addEventListener("load", o, !1))

This is a custom version of the script they give you to place in your apps <head></head> tag. However, you’ll notice we’ve added a setTimeout function that will delay the loading of the full Intercom script. This gives your application a chance to load everything else without competing for network or CPU time.

However, as Intercom is no longer guaranteed to be available, you’ll need to use greater caution when interacting with it.

This exact same concept can be applied to just about every 3rd party script you might load in. We also use it with Google Analytics, where we initialize the command queue, but defer loading the actual script. Obviously, this can cause tracking issues with short sessions, but that is the tradeoff you need to make if performance is your primary goal.

Leave a Comment