1

I am building a website with SvelteKit. SvelteKit makes things a blast, especially server-side rendering is easy. Currently, I am serving the website using SvelteKit's node.js adapter due to the high amount of database generated web pages.

However, despite the server-side rendering, I am facing an issue of low-performance mobile connections, as per PageSpeed Insights.

First Contentful Paint is slow (4.0s) which I find quite unacceptable myself.

enter image description here

I analyze this issue mostly to do with blocking the loading of vendor.js.

Node.js adapter loads the vendor.js as the following:

<link rel="modulepreload" href="/_app/chunks/vendor-87f5cdbf.js">

Some other modulepreload bundles are also included, but they do not cause significant loading time

enter image description here

vendor.js is 350kb and the cause of the most blocking for the site load.

enter image description here

My question is

  • How can I analyse what goes into vendor.js
  • How can I reduce vendor.js size in SvelteKoit
  • How can I make some of the JavaScript code load lazily, as for the server-side rendering I believe most of this code could be run after the first content full paint

My frontend is open source for further information. I am using svelte-bootstrap library.

2
  • When running your site (on web.dev/measure), the biggest issue is to reduce image size for mobile
    – coyotte508
    Dec 24, 2021 at 10:59
  • There is underlying Vite.js issue that forces the blocking loading of JavaScript files - against the web development best pratices. I wrote a detailed bug report. Dec 24, 2021 at 11:11

3 Answers 3

7

Rather than doing this complicated rewriting of modulepreload scripts, you might want to disable the vendor chunk instead:

export default {
    kit: {
        vite: {
            build: {
                rollupOptions: {
                    output: {
                        manualChunks: undefined
                    }
                }
            }
        }
    }
}

More info in the Vite issue tracker: https://github.com/vitejs/vite/issues/3731

2
  • didn't really change anything for me in terms of lighthouse scoring May 5, 2022 at 8:31
  • The vedor chunk has been removed by default in the latest versions of Vite so this is no longer required
    – Ben McCann
    May 5, 2022 at 16:01
2

Below is a complete transformer <link rel="modulepreload"> -> <script type="module" async"> hook transformed based on cheetah library. Note that this transformer adds SSR loading penalty and the proper solution is to fix Vite.

The frontpage now achievees the perfect 100 score on PageSpeed test for desktop connections, 90 for mobile connections.

  • tags are moved to the end of the `` using the body hook, as inspirsed by the answer ferom coyotte508
  • This will ensure CSS files are always loaded first and the First Contentful Paint is fast, after which which the web browser starts to load JavaScript to make the page interactive

  • I managed to improve Mobile 3G FCP from 4 seconds to 2.5 seconds which is a very significant improvement in the user experience. For slow 3G this number went from over 9 seconds to 3.5 seconds which is even more significant improvement.

Other optimisations I had to do:

  • Manually optimize Boostrap CSS bundle by removing unneeded components and reducing number of autogenerated CSS class variations (alert-xxxx, mt-, etc.). The original bundle was over 500 kb uncompressed, the current bundle is 231 kb uncompressed.

  • Self-host Google fonts - reduces some TLS handshake time for mobile connections

  • Manually remove some small CSS files imported in Svelte components and move these styles to __layout.svelte using :global selector to reduce the number of HTTP requests made for CSS files

  • Make sure all <img> tags have width and height attributes set to reduce cumulative layout shifts

  • Enable extrernalFetch hook on SSR to reduce the SSR page load times by optimizing backend API call round-trip times

  • Disable manual chunks. I have no idea how SvelteKit + Vite + Rollup interact, but this seems to give additional 0.2 seconds on the mobile page loads when massive vendor.js chunk is not generated.

My hooks.ts:

import type { Handle } from '@sveltejs/kit';
import * as cheerio from 'cheerio';
import {siteMode} from "$lib/config";


/**
 * Modifies the response in-place to fix the link rel="modulepreload" issue.
 *
 * Note that this fix causes significant server-side processing time increase -
 * do not use long term, only proper fix is to fix Vite.
 *
 * For the source of the issue of loading times please see https://github.com/vitejs/vite/issues/5120
 *
 */
function fixLinkModulePreloadIssue(response: ServerResponse) {

    if(!response.body) {
        throw new Error("text/html response was missing body");
    }
    const $ = cheerio.load(response.body);

    const body = $("body");

    // Replace <link rel="modulepreload"> with <script type="module">
    // https://api.jquery.com/replacewith/
    //$('link[rel="modulepreload"]').replaceWith(function() {
    //  const src = $(this).attr('href');
    //// The defer attribute has no effect on module scripts — they defer by default.
    //  return `<script type="module" src="${src}"></script>`;
    //});

    $('link[rel="modulepreload"]').each(function(idx, elem) {
        const $this = $(this);
        const src = $this.attr('href');
        $(`<script type="module" async src="${src}"></script>`).appendTo(body);
        $this.remove();
    });

    // TODO: Does not have effect if we put scripts at the end of the body
    // Move starter section to the <body> end
    // Assume we have only one <script type="module"> in our generated <head>
    // const starter = $("head script[type='module']");
    //starter.appendTo(body);
    //starter.remove();

    response.body = $.html();
}


export const handle: Handle = async ({ request, resolve }) => {

    // TODO https://github.com/sveltejs/kit/issues/1046
    if (request.query.has('_method')) {
        request.method = request.query.get('_method').toUpperCase();
    }

    const response = await resolve(request);

    // Fix modulepreload issue
    // https://stackoverflow.com/a/70472372/315168

    if (response.headers["content-type"] === "text/html") {
        // Only try to transform HTML pages,
        // do not touch binary etc. loads
        fixLinkModulePreloadIssue(response);
    }

    return response;
};


/**
 * Shortcut fetch() API requests on the server-side rendering.
 *
 * See https://github.com/tradingstrategy-ai/proxy-server/blob/master/Caddyfile
 *
 * @type {import('@sveltejs/kit').ExternalFetch}
 */
export async function externalFetch(request) {

    if(siteMode == "production") {

        // Write API URL to the internal network
        // TODO: Make these URLs part of config
        const publicHost = "https://tradingstrategy.ai/api";
        const internalHost = "http://127.0.0.1:3456"

        if (request.url.startsWith(publicHost)) {
            // clone the original request, but change the URL
            request = new Request(
                request.url.replace(publicHost, internalHost),
                request
            );}

    }
    return fetch(request);
}
0
1

A hacky solution to make some javascript load asynchronously would be to create a handle hook in your hooks.ts file.

With it you can edit the html sent to the client, and replace <link rel="module preload"> with <script defer async>.

It would look something like that:

// horrible hack
export async function handle({ request, resolve }: Parameters<Handle>[0]): Promise<ServerResponse> {
  const response = await resolve(request);

  if (typeof response.body === "string") { // not sure if necessary
    response.body = response.body.replace(
      /<link rel="modulepreload" href="(\/_app\/chunks\/vendor-[^.]+\.js)">/, 
      (_, url) => `<script defer async src="${url}">`
    );
  }

  return response;
}

Note that it's prone to break if the format of the html emitted by SvelteKit changes.

0

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.