Optimizing web builds
A rich Flutter Web app can easily download 6–8 MB before the first screen even paints.
For the full DOCX playground, we set a 3 MB Brotli budget for main.dart.wasm. Over a few focused passes on Flutter 3.50.1, we cut its WebAssembly (Wasm) core from ~6.6 MB to under 3 MB, split 238 deferred .wasm modules out of startup, and dropped total cold-start downloads to 4.50 MB on standard documents (5.57 MB on our 26-page rich showcase).
Pick your own budget
3 MB is our budget for the full DOCX playground. Choose a number that fits your app—a focused rich-text input can aim much lower, while a larger suite may set a different target—and check it on every release.
1. Use Flutter 3.50.1's Wasm build flags
Flutter 3.50.1 gives you four built-in wins out of the box:
- Split Wasm modules (
--enable-wasm-deferred-loading) — Turns Dartdeferred asimports into separate.wasmchunks viadart2wasm. Customize chunk URLs influtter_bootstrap.js. - Maximum shrinking (
--optimization-level=4) — Tighter dead-code removal and inlining in release Wasm builds. - Icon tree-shaking (
--tree-shake-icons) — On by default in release mode; drops unused glyphs from icon fonts automatically. - Multi-threaded SkWasm — Flutter's SkWasm renderer paints off the main thread when
COOP/COEPheaders are set, with multi-threaded glyph stability fixed in 3.50.1.
sh
flutter build web --wasm --release --optimization-level=4 --enable-wasm-deferred-loadingOnly depend on the Vyuh Document packages you actually need—skip math, diagrams, or file codecs if your app doesn't use them.
2. Load each feature only when triggered
Sort every feature into four clear buckets so first paint stays tiny:
| When it loads | Trigger | Examples |
|---|---|---|
| 1. First paint | App opens | Editor shell, core layout, tree-shaken UI icons, 4 core font weights, English (en) |
| 2. Enters view | Block scrolls on screen | Math & diagram engines, extra font weights, emoji/CJK/RTL fallbacks |
| 3. User clicks | Opens panel or menu | Property inspectors, dialogs, syntax grammars, other languages |
| 4. File action | Open, drop, paste, export | DOCX/PDF/HTML/Markdown codecs, background WebAssembly workers |
Avoid two common traps that erase deferred-loading wins:
- Off-screen layout triggers — Don't spin up heavy runtimes during background pagination or off-screen measurement, or a 25-page document will download math and diagram engines on boot even when those blocks live on page 12. Wait until the widget mounts in the viewport (
initState). - Startup timers for background workers — Prewarming a 400+ KB WebAssembly worker 250 ms after first frame still hits the cold-boot network waterfall. Wait for drag-enter, file open, or an export click.
3. Avoid Dart2Wasm's devirtualization trap
Writing import '...' deferred as foo; is not enough on its own. Because dart2wasm runs whole-program optimization, if boot code calls a method through an abstract interface whose concrete class lives in a deferred library—or imports an umbrella barrel that re-exports concrete factories—the compiler can devirtualize the call and hoist the entire implementation graph back into main.dart.wasm.
Keep every deferred boundary airtight with three rules:
- Separate contracts from implementations. Put only plain DTOs and schema IDs in a tiny
contracts.dartlibrary (~2 KB) imported at boot. - Cross the boundary via top-level deferred functions. Call
await module.loadLibrary()inside anasyncentry point before instantiating the concrete implementation—never return a deferred subtype for boot code to dispatch interface methods on. - Skip umbrella barrels in boot files. Import targeted contract sub-libraries instead of package barrels that transitively reach parsers, codecs, or graphics engines.
dart
// Boot UI imports only contracts + the trigger below.
import 'export_contracts.dart';
import 'pdf_export_impl.dart' deferred as pdf;
Future<List<int>> exportOnClick(ExportRequest req) async {
await pdf.loadLibrary(); // downloads the .wasm chunk on first click
return pdf.encodePdf(req);
}Use the same pattern inside a widget's initState() for viewport-triggered engines (math, diagrams).
Verify every boundary in the build output
After adding a deferred as boundary, confirm that main.dart.wasm actually shrank and a new main.dart_module*.wasm chunk appeared. If main.dart.wasm did not drop, a transitive barrel import or devirtualized interface call is still pinning the graph at boot.
4. Put your fonts on a diet
Every font under fonts: in pubspec.yaml goes into FontManifest.json and downloads eagerly at startup. Keep fonts: limited to tree-shaken UI icons (plus at most one core UI monospace face), and move document fonts, extra weights, and emoji to assets: to load on demand with FontLoader:
yaml
flutter:
uses-material-design: true # eager: tree-shaken UI icons only
assets: # lazy: loaded on demand via FontLoader
- assets/fonts/Roboto-Light.ttf
- assets/fonts/NotoEmoji-Regular.ttf- Start with 4 weights (
400,400i,700,700i) and load Thin, Light, Medium, or Black only when a document uses them, registering faces incrementally in the background and triggering a clean relayout without blocking first paint. - Reuse existing UI faces (like your code monospace font) by family name instead of fetching a duplicate copy under another alias.
- Guard against accidental 1 MB emoji fetches—common symbols like
✓sit inside Unicode blocks that overlap emoji ranges, so route standard symbols to a tiny symbol font (~3 KB) instead of waking a 1 MB emoji font on a checklist.
5. Move big data and extra languages out of Wasm
- Externalize large tables and sample media as compressed assets instead of Dart source constants.
- Lazy-load extra languages (e.g. with
slang'slazy: true): keep English compiled in, and load each extra language as a ~4–6 KB deferred chunk. See Localization. - Pool heavy Web Workers and pass results back as transferable
ArrayBuffers instead of spawning a fresh worker per call.
6. Compress offline with Brotli q11 and split caching
Pre-compressing offline at Brotli level 11 shrinks Wasm modules and fonts far more than on-the-fly CDN compression.
- Pre-compress every static asset (
.wasm,.mjs,.js,.json,.ttf,.otf) and serve withContent-Encoding: br. - Hash every sub-asset (
?v=<sha256>)—main.dart.wasm, deferred chunks, andFontManifest.jsonfonts—so they safely use 1-yearimmutablecaching. - Version
skwasm.js+skwasm.wasmatomically under one hash directory (canvaskit/v-<hash>/) viaflutter_bootstrap.jsso cached deploys never pair a mismatched JS wrapper with an older Wasm binary. - Keep unversioned entrypoints on
no-cache(index.html,flutter_bootstrap.js, bare.wasm/worker paths) so deploys go live immediately. Only setno-transformon.brresponses so non-Brotli proxies keep edge gzip. - Send
COOP: same-originandCOEP: credentiallessto unlock multi-threaded SkWasm while still permitting third-party images and fonts without per-hostCORPheaders.
7. Measure on a clean cold boot
Always measure in an incognito window with Disable cache checked. On the Vyuh Document playground (0.87 → 0.88), auditing actual cold-boot traffic cut another 31–44% off first-visit downloads:
| Cold-boot download (Brotli q11) | Before (0.87) | After (0.88) | Saved |
|---|---|---|---|
main.dart.wasm | 2.97 MB | 2.97 MB | Within our 3 MB budget |
Eager FontManifest.json fonts | 1,332 KB | 67 KB | −95% |
| Background DOCX worker at boot | 425 KB | 0 KB | Waits for file open/drop |
| Off-screen math & diagram assets | 350 KB | 0 KB | Waits for scroll into view |
| Total (standard document) | 8.07 MB | 4.50 MB | −44% |
| Total (26-page rich showcase) | 8.07 MB | 5.57 MB | −31% |
| Initial HTTP requests | 45+ | ~19 | −58% |
Quick release checklist
Official references
| Capability | Documentation |
|---|---|
Flutter Wasm (--wasm, -O4, deferred loading, COOP/COEP) | Support for WebAssembly (Wasm) in Flutter |
| SkWasm & CanvasKit web renderers | Flutter web renderers |
Custom flutter_bootstrap.js & loaders | Flutter web app initialization |
| Flutter 3.50.1 updates | Flutter release notes |
Bundled fonts & dynamic FontLoader | Custom fonts · FontLoader |
Dart deferred as & dart2wasm | Lazily loading a library · Dart WebAssembly |
| Lazy deferred localization | slang on pub.dev |
| Caching, Brotli, isolation & Workers | Cache-Control · Content-Encoding · COOP · COEP · Transferable objects |
Next
- Packages — pick only the packages your app needs.
- Localization — ship multiple languages with zero boot cost.
- Fonts and images — load document fonts and images on demand.