new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Svelte · SvelteKit · all subjects

performance

43 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

SvelteKit provides build optimizations

SvelteKit includes build optimizations to load only the minimal required code.

prerender option required for adapter-static

When using adapter-static, you must add the prerender option to your root layout file (src/routes/+layout.js) and set export const prerender = true to enable prerendering of pages.

Performance overhead of tracing and instrumentation

Tracing and observability instrumentation can have nontrivial overhead. Consider whether tracing is necessary for your use case, or whether it might be more appropriate to enable it only in development and preview environments.

Font preloading in handle hook

SvelteKit does not preload fonts by default, since this may cause unnecessary files such as unused font weights to be downloaded. However, preloading fonts correctly can improve perceived performance. Fonts can be preloaded in the handle hook by calling resolve with a preload filter that includes fonts.

Built-in performance optimizations in SvelteKit

SvelteKit includes the following built-in performance optimizations: code-splitting so only necessary code for the current page is loaded; asset preloading to prevent waterfalls of files requesting other files; file hashing so assets can be cached forever; request coalescing so data from separate server load functions is grouped into a single HTTP request; parallel loading so separate universal load functions fetch data simultaneously; data inlining so requests made with fetch during server rendering can be replayed in the browser without a new request; conservative invalidation so load functions are only re-run when necessary; prerendering configurable per-route for pages without dynamic data; and link preloading so data and code requirements for client-side navigation are eagerly anticipated.

Use preview mode not dev mode for performance testing

A site running locally in dev mode will exhibit different behaviour than the production app. Performance testing should be done in preview mode after building the app.

Use dynamic import for conditionally needed code

Code imported with static import declarations will be automatically bundled with the rest of the page. If code is needed only when some condition is met, use the dynamic import(...) form to selectively lazy-load the component.

Link preloading configured by default

Link preloading is used to speed up client-side navigations by eagerly preloading necessary code and data, using link options. This is configured by default on the body element when creating a new SvelteKit app.

Use promises in load function for non-essential slow data

For slow-loading data that is not needed immediately, the object returned from a load function can contain promises rather than the data itself. For server load functions, this will cause the data to stream in after the navigation or initial page load.

Avoid waterfalls with server load functions

Waterfalls occur when a series of requests is made sequentially, which is costly for performance especially on slower networks. Use server load functions to make requests to backend services that are dependencies, rather than making requests from the browser. This avoids waterfalls because server load functions rarely involve round trips with high latency. However, server load functions can still have waterfalls; it is typically more performant to issue a single query with a database join rather than making sequential database queries.

SPA mode causes waterfalls

Enabling single page app (SPA) mode causes waterfalls. With SPA mode, an empty page is generated which fetches JavaScript, which ultimately loads and renders the page. This results in extra network round trips before a single pixel can be displayed.

Tools for diagnosing performance issues

Google PageSpeed Insights and WebPageTest are excellent ways to understand the performance characteristics of a deployed site. Browser developer tools are also useful: Chrome includes Lighthouse, Network, and Performance devtools; Edge includes Lighthouse, Network, and Performance devtools; Firefox includes Network and Performance devtools; Safari includes performance enhancement tools.

Use server-side analytics instead of JavaScript-based analytics

To minimize third-party scripts running in the browser, consider using server-side implementations of analytics instead of JavaScript-based analytics. Many platforms with SvelteKit adapters offer server-side analytics, including Cloudflare, Netlify, and Vercel.

Use Partytown for third-party scripts

To run third-party scripts in a web worker (which avoids blocking the main thread), use Partytown's SvelteKit integration.

Subsetting fonts to reduce file size

Font file sizes can be reduced by subsetting fonts, which involves keeping only the characters or glyphs that are actually needed.

Use rollup-plugin-visualizer to identify large packages

The rollup-plugin-visualizer package can help identify which packages are contributing the most to the size of a site. Manual inspection of the build output can also identify code removal opportunities using build: { minify: false } in Vite config (but remember to undo that before deploying).

Svelte 5 is smaller and faster than earlier versions

Svelte 5 is smaller and faster than Svelte 4, which is smaller and faster than Svelte 3. Running the latest version of Svelte is recommended.

Video optimization techniques

Video files can be very large and should be optimized: compress videos with tools such as Handbrake and consider converting to web-friendly formats such as .webm or .mp4; lazy-load videos below the fold with preload="none" (though this will slow down playback when initiated); strip the audio track out of muted videos using a tool like FFmpeg.

Use enhanced-img package for image optimization

Svelte provides the @sveltejs/enhanced-img package for making image optimization easier. Additionally, Lighthouse is useful for identifying image files that are the worst offenders for performance.

Image optimization best practice: large images and sizes attribute

For images much larger than mobile device width (roughly 400px), such as hero images, specify the `sizes` attribute so smaller images are served on smaller devices.

Image optimization best practice: fetchpriority for LCP images

For important images such as the largest contentful paint (LCP) image, set `fetchpriority="high"` and avoid `loading="lazy"` to prioritize loading as early as possible.

Image optimization best practice: prevent layout shift

Give images a container or styling so they are constrained and do not jump around while loading, affecting cumulative layout shift (CLS). The `width` and `height` attributes help the browser reserve space while the image loads. @sveltejs/enhanced-img automatically adds `width` and `height` for you.

Image optimization best practice: alt text

Always provide good `alt` text for images. The Svelte compiler will warn if alt text is missing.

Image optimization best practice: avoid em/rem in sizes

Do not use `em` or `rem` units in `sizes` attributes or change the default size of these measures. When used in `sizes` or `@media` queries, `em` and `rem` are defined as the user's default `font-size`, which may differ from the actual font-size used by CSS for layout. Do not use CSS like `html { font-size: 62.5%; }` as this causes the browser preloader to reserve a different amount of space than the actual CSS object model.

@sveltejs/enhanced-img basic usage with enhanced:img tag

Use `<enhanced:img>` tag instead of `<img>` in Svelte components and reference the image file with a Vite asset import path. At build time, the `<enhanced:img>` tag is replaced with an `<img>` wrapped by a `<picture>` element that provides multiple image types and sizes.

@sveltejs/enhanced-img source image resolution

Provide images at the highest resolution needed because images can only be downscaled without losing quality. For HiDPI or retina displays, provide images at 2x the resolution they will be displayed at. @sveltejs/enhanced-img will automatically serve smaller versions to smaller devices.

@sveltejs/enhanced-img CSS selector escaping

To use a tag name CSS selector for `<enhanced:img>` in a `<style>` block, escape the colon as `enhanced\:img`.

@sveltejs/enhanced-img dynamic image selection

Images can be dynamically chosen by manually importing an image asset with the `?enhanced` query parameter and passing it to `<enhanced:img>`. This is useful for collections of static images that need to be dynamically selected or iterated over.

@sveltejs/enhanced-img plugin capabilities

@sveltejs/enhanced-img is a Vite plugin that provides image processing on top of Vite's built-in handling. It serves smaller file formats like avif or webp, automatically sets the intrinsic width and height attributes to avoid layout shift, creates images of multiple sizes for various devices, and strips EXIF data for privacy. It works in any Vite-based project including SvelteKit.

@sveltejs/enhanced-img build-time limitation

@sveltejs/enhanced-img can only optimize files located on the machine during the build process. It cannot optimize images from external sources like a database, CMS, or backend path.

@sveltejs/enhanced-img plugin installation

Install @sveltejs/enhanced-img with `npm i -D @sveltejs/enhanced-img`. The plugin must be added to the Vite config in the `plugins` array and must come before the SvelteKit plugin.

@sveltejs/enhanced-img build caching

The first build with @sveltejs/enhanced-img will take longer due to the computational expense of transforming images. Subsequent builds will be fast because the build output is cached in `./node_modules/.cache/imagetools`.

@sveltejs/enhanced-img with import.meta.glob

When using Vite's `import.meta.glob` with @sveltejs/enhanced-img, specify the `enhanced` transformation via a custom query parameter. SVG images are currently only supported statically, not with glob imports.

@sveltejs/enhanced-img intrinsic dimensions

The `width` and `height` attributes are optional for `<enhanced:img>` because they can be inferred from the source image and automatically added during preprocessing. To prevent layout shift, the browser needs these attributes to reserve the correct amount of space. If you want different dimensions, style them with CSS and specify `height: auto` if one dimension should be automatically calculated.

Vite automatic asset processing and caching

Vite automatically processes imported assets for improved performance. Hashes are added to filenames to enable caching. Assets smaller than the `assetsInlineLimit` value are inlined. This applies to assets referenced via the CSS `url()` function as well.

@sveltejs/enhanced-img srcset and sizes attribute

For large images like hero images that take the full width of the design, specify the `sizes` attribute so smaller versions are requested on smaller devices. If `sizes` is specified, @sveltejs/enhanced-img generates multiple image sizes and populates the `srcset` attribute. If `sizes` is not provided, a HiDPI and standard resolution image are generated.

@sveltejs/enhanced-img minimum image width

The smallest picture generated automatically by @sveltejs/enhanced-img has a width of 540px. Custom widths can be specified using the `w` query parameter with semicolon-separated values.

@sveltejs/enhanced-img per-image transforms

Per-image transforms such as blur, quality, flatten, or rotate operations can be applied by appending a query string to the image source. For example: `src="./path/to/your/image.jpg?blur=15"`. The full list of transform directives is available in the imagetools repository documentation.

CDN-based image optimization approach

CDN-based image optimization allows dynamic optimization of images not accessible at build time, such as images from a CMS or backend. CDNs can serve appropriate formats based on the User-Agent header without requiring `<picture>` tags. Trade-offs include setup overhead, usage costs, and potential lazy generation with negative performance impact on low-traffic sites.

CDN image optimization libraries

@unpic/svelte is a CDN-agnostic library with support for many CDN providers. Specific CDNs like Cloudinary and content management systems like Contentful, Storyblok, and Contentstack also offer Svelte support with built-in image handling.

Image optimization best practice: mix solutions

Different image solutions can be mixed in one project. For example, use Vite's built-in handling for meta tag images, @sveltejs/enhanced-img for display images on the homepage, and a dynamic CDN approach for user-submitted content.

Image optimization best practice: use CDN globally

Consider serving all images via CDN regardless of the image optimization type used, because CDNs reduce latency by distributing copies of static assets globally.

Image optimization best practice: source resolution

Original images should have good quality and resolution, with 2x the width they will be displayed at to serve HiDPI devices. Image processing can size images down to save bandwidth for smaller screens, but upscaling is wasteful.

Give your agent this brain