Unity WebGL
WebAssembly
Game Optimization
Browser Games
Memory Management
Unity 6
JavaScript Interop

Unity WebGL Performance Guide: WebAssembly Loading, Memory Architecture & Browser Caching

14 min read
Eshan Naithani

Shipping a Unity game to the browser via WebGL (Unity Web) introduces an execution model that is fundamentally different from native iOS, Android, or Windows builds. Inside a browser tab, your C# code is cross-compiled via IL2CPP into WebAssembly (.wasm), file I/O is emulated in memory or IndexedDB, multithreading is constrained by SharedArrayBuffer cross-origin isolation rules, and GPU rendering runs through the WebGL 2.0 state machine on top of ANGLE, Metal, D3D11, or Vulkan.

Because browser tabs enforce strict memory ceilings and users abandon web pages that stall during initial download, optimizing a Unity WebGL build requires coordinating three layers simultaneously:

  1. Network Delivery & Streaming Compilation (.wasm.br, .data.br, HTTP headers, and IndexedDB caching).
  2. Runtime Memory Architecture (WebAssembly linear heap, GPU texture compression, and garbage collection).
  3. Browser Host Integration (createUnityInstance lifecycle, devicePixelRatio scaling, and .jslib JavaScript interop).

Scope Note: This guide focuses on runtime WebAssembly architecture, HTTP server delivery, browser memory profiling, .jslib interop, and deployment diagnostics.


1. Anatomy of a Unity WebGL Build & Real Compression Benchmarks

When Unity builds a WebGL target, it outputs four primary artifacts inside the Build/ directory:

  1. [BuildName].loader.js: Lightweight JavaScript bootstrapper (~25 KB) that detects browser capabilities, manages the IndexedDB cache, and downloads the remaining artifacts.
  2. [BuildName].framework.js(.br/.gz): Emscripten JavaScript runtime bindings bridging WebGL 2, WebAudio, DOM input, and .jslib plugins to the WebAssembly module.
  3. [BuildName].wasm(.br/.gz): Your compiled C++ engine code and IL2CPP-translated C# assemblies in binary WebAssembly format.
  4. [BuildName].data(.br/.gz): The packed virtual filesystem containing scenes, serialized prefabs, textures, meshes, and audio assets included in the initial build scenes.

Verified Build Size Comparison: Raw vs. Brotli (AI NPC Demo)

To see why native Brotli (.br) compression and proper HTTP server headers are mandatory, here are the exact artifact sizes from the playable Unity 6 WebGL build powering our AI NPC Behavior & NavMesh Architecture Demo (public/webgl/ai-npc-system/Build/):

Build ArtifactUncompressed SizeBrotli (.br) SizeNetwork Transfer Reduction
NPC.wasm (Engine + IL2CPP Code)48.11 MB (48,108,032 B)8.43 MB (8,431,208 B)-82.5%
NPC.data (Scenes, NavMesh, Assets)13.61 MB (13,606,152 B)5.17 MB (5,174,029 B)-62.0%
NPC.framework.js (JS Runtime Glue)455.37 KB (455,369 B)76.01 KB (76,006 B)-83.3%
NPC.loader.js (Bootstrapper)26.98 KB (26,982 B)26.98 KB (Uncompressed JS)—
Total Initial Payload62.20 MB13.71 MB-78.0% Total Reduction

Without Brotli compression, visitors would download 62.2 MB over the wire before the first frame renders. With Brotli enabled, the transfer payload drops to 13.71 MB.


2. WebAssembly Streaming Compilation & HTTP Content-Encoding Headers

Modern browsers support WebAssembly.instantiateStreaming(), which compiles .wasm bytecode into native machine instructions while the file is still downloading over the network—eliminating a 2–5 second post-download freeze on mid-range devices.

However, WebAssembly.instantiateStreaming() only activates if your web server or CDN returns the exact MIME type application/wasm alongside the matching Content-Encoding header (br for Brotli or gzip for Gzip).

Next.js / Node.js Hosting Configuration (next.config.ts)

When hosting Unity WebGL builds inside a Next.js public/ directory (as we do on this website), configure custom response headers in next.config.ts so compressed .br or .gz (.unityweb) files are served with the required headers:

TYPESCRIPT
// Example next.config.ts headers configuration for Unity WebGL Brotli builds
async headers() {
  return [
    {
      source: "/webgl/:project/Build/:file*.wasm.br",
      headers: [
        { key: "Content-Type", value: "application/wasm" },
        { key: "Content-Encoding", value: "br" },
        { key: "Cache-Control", value: "public, max-age=31536000, immutable" },
      ],
    },
    {
      source: "/webgl/:project/Build/:file*.js.br",
      headers: [
        { key: "Content-Type", value: "application/javascript" },
        { key: "Content-Encoding", value: "br" },
        { key: "Cache-Control", value: "public, max-age=31536000, immutable" },
      ],
    },
    {
      source: "/webgl/:project/Build/:file*.data.br",
      headers: [
        { key: "Content-Type", value: "application/octet-stream" },
        { key: "Content-Encoding", value: "br" },
        { key: "Cache-Control", value: "public, max-age=31536000, immutable" },
      ],
    },
  ];
}

Why You Should Avoid Decompression Fallback in Production

In Project Settings > Player > WebGL > Publishing Settings, Unity offers a Decompression Fallback checkbox. When enabled, Unity bundles a JavaScript Brotli/Gzip decompressor inside .loader.js and renames files to .unityweb.

  • The Downside: If Decompression Fallback is used, the browser cannot use native HTTP decompression or WebAssembly.instantiateStreaming(). Instead, JavaScript must allocate a huge temporary ArrayBuffer in RAM, decompress the entire .wasm and .data payload on the main CPU thread, and only then compile the WebAssembly module.
  • Best Practice: Leave Decompression Fallback unchecked for self-hosted production deployments and configure Content-Encoding: br at the CDN/server layer. Enable Name Files As Hashes so Cache-Control: immutable never serves stale files after an update.

3. Browser Caching (Data Caching & IndexedDB)

Downloading the .data file (and remote Unity Addressables bundles) on every page refresh wastes bandwidth and hurts repeat-session retention.

  1. Enable Data Caching: In Player Settings > Publishing Settings, check Data Caching. Unity's loader intercepts the network response for [BuildName].data and writes it into the browser's IndexedDB under the UnityCache database.
  2. Cache Key & Invalidation: Unity keys the IndexedDB cache entry using the URL and content hash (when Name Files As Hashes is enabled) or productVersion. Always increment PlayerSettings.bundleVersion (productVersion) or enable Name Files As Hashes on every deployment so returning players do not load a mismatched .data archive against a new .wasm binary.
  3. Syncing Application.persistentDataPath (IDBFS): Player saves written to Application.persistentDataPath or PlayerPrefs in WebGL reside in an in-memory Emscripten filesystem (MEMFS) synced to IndexedDB (IDBFS). In Unity 6 WebGL templates (index.html), uncomment config.autoSyncPersistentDataPath = true; inside the loader config object to ensure file writes flush automatically to IndexedDB before the user closes the browser tab.

4. Unity Build Size Analysis via Editor.log

Before optimizing assets blindly, inspect Unity's deterministic build breakdown. Immediately after running a WebGL build, open the Console window, click the three-dot menu in the top-right corner, and select Open Editor Log.

Search the log for Build Report and Uncompressed usage by category:

TEXT
Build Report
Uncompressed usage by category (Percentages based on user generated assets only):
Textures               42.4 mb	 58.2%
Meshes                 11.8 mb	 16.2%
Animations              6.1 mb	  8.4%
AudioClips              5.4 mb	  7.4%
Shaders                 3.9 mb	  5.3%
Other Assets            3.3 mb	  4.5%

High-Impact Reductions Based on Editor.log

  • Shader Variant Stripping (Shaders > 3 MB): WebGL 2 compiles shaders into GLSL ES 3.0 and translates them via ANGLE at runtime. Massive shader variants cause both large .data files and severe frame hitches the first time a material appears on screen. Under Project Settings > Graphics, strip unused fog modes, lightmap modes, and instancing variants, and remove unused URP renderer features.
  • Engine & Managed Code Stripping (NPC.wasm): In Publishing Settings, enable Strip Engine Code, set Managed Stripping Level to High, set IL2CPP Code Generation to Faster (smaller) builds, and set Enable Exceptions to Explicitly Thrown Exceptions Only (or None once stable).

5. WebGL Memory Architecture & Browser Profiling

Unlike a desktop OS that pages virtual memory to disk, a browser tab runs inside a sandbox with a hard memory ceiling. Understanding where memory lives in Unity WebGL is essential to preventing RuntimeError: memory access out of bounds and mobile Safari tab reloads.

Code
┌────────────────────────────────────────────────────────────────────────────┐
│                        BROWSER TAB MEMORY FOOTPRINT                        │
├──────────────────────────┬─────────────────────────┬───────────────────────┤
│  1. Wasm Linear Memory   │   2. Browser JS Heap    │   3. WebGL 2 GPU RAM  │
│  (ArrayBuffer / Heap)    │   (DOM + Emscripten)    │   (VRAM / Unified)    │
├──────────────────────────┼─────────────────────────┼───────────────────────┤
│ • IL2CPP Managed Heap    │ • Decompression Buffers │ • Compressed Textures │
│ • Unity Native C++ Heap  │ • WebAudio Decoded PCM  │ • RenderTextures      │
│ • AssetBundle Buffers    │ • JS Interop Objects    │ • Mesh Vertex Buffers │
└──────────────────────────┴─────────────────────────┴───────────────────────┘

Crucial WebAssembly Memory Nuance: Heap Growth Cannot Shrink

The WebAssembly linear memory space is backed by a single contiguous JavaScript ArrayBuffer.

  • When your game allocates peak memory (for example, loading a heavy scene while the previous scene is still in memory), the Wasm heap grows (memory.grow).
  • WebAssembly specification limitation: Once a Wasm ArrayBuffer grows to a high-water mark (e.g., 768 MB), it can never shrink back down to the browser OS for the lifetime of that unityInstance, even if you call Addressables.Release() or GC.Collect(). Freeing assets makes space reusable inside the existing Wasm heap for future Unity allocations, but the browser tab still holds the peak ArrayBuffer allocation.
  • Architectural Takeaway: Avoid overlapping memory spikes during scene transitions. Unload the current level's Addressable assets before loading the next level's heavy bundles so the Wasm high-water mark stays low.

GPU Texture Compression: Desktop vs. Mobile Browsers

Never ship uncompressed RGBA32 textures in WebGL. In Build Profiles / Build Settings > WebGL > Texture Compression Format:

  • ASTC: Best for mobile browsers (iOS Safari, Android Chrome) and Apple Silicon Macs, which have native hardware ASTC decoding.
  • DXT (BC1/BC3): Supported natively by desktop Windows/Linux GPUs, but unsupported on mobile GPUs (where it gets decompressed to raw RGBA32 in software, multiplying RAM by 4x–8x!).
  • Basis Universal / Dual Target Strategy: For cross-device WebGL games, either use ASTC when mobile browser stability is your primary constraint (since desktop PCs have abundant RAM while iOS Safari crashes easily) or use Basis Universal / dual desktop-vs-mobile asset bundles.

Profiling Memory in Chrome DevTools & Unity Profiler

  1. Unity Autoconnect Profiler: Build with Development Build and Autoconnect Profiler enabled to inspect C# GC allocations and native Texture2D / Mesh memory inside the Unity Editor.
  2. Chrome DevTools Memory Tab: Open Chrome More Tools > Task Manager (Shift+Esc) alongside DevTools > Memory to monitor total tab footprint, JS heap size, and GPU memory simultaneously.

6. Loading-Screen UX & devicePixelRatio Resolution Scaling

Deferred Click-to-Load Pattern

Initializing a 15 MB–50 MB WebGL engine automatically on window.onload blocks the browser main thread, harms Core Web Vitals (Total Blocking Time and Largest Contentful Paint), and triggers mobile browser memory pressure before the user even intends to play.

On eshannaithani.com, our WebGLEmbed.tsx component uses a lightweight interactive preview overlay that defers loading the Unity canvas until the user explicitly clicks Load Interactive Demo. For the full React/Next.js implementation, see our Unity WebGL Integration Guide for React & Next.js.

Clamping devicePixelRatio on High-DPI & Mobile Displays

By default, Unity WebGL matches the canvas render resolution to window.devicePixelRatio. On an iPhone Pro or 4K Retina MacBook (devicePixelRatio = 3), a 960x600 CSS canvas renders internally at 2880x1800 (9x the pixel count)—causing severe GPU fragment shader throttling and huge MSAA framebuffer allocations.

Inside your WebGL index.html template, clamp config.devicePixelRatio on mobile and high-DPI displays:

JAVASCRIPT
// Clamp devicePixelRatio so Retina/Mobile displays don't render at 3x native pixel density
const maxPixelRatioMobile = 1.5;
const maxPixelRatioDesktop = 2.0;
const isMobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);

config.devicePixelRatio = Math.min(
  window.devicePixelRatio || 1,
  isMobile ? maxPixelRatioMobile : maxPixelRatioDesktop
);

7. JavaScript Interoperability (.jslib) Performance Best Practices

When communicating between Unity C# and the host web application (such as React, Vue, or an analytics/ad SDK), never use the deprecated Application.ExternalEval or Application.ExternalCall. Instead, create a .jslib file inside Assets/Plugins/WebGL/.

Avoiding String Allocation Bottlenecks in .jslib

Marshaling strings across the C#-to-JavaScript boundary requires UTF-8 encoding and heap allocation (stringToNewUTF8 / _free). Calling string-heavy .jslib methods every frame inside Update() creates avoidable GC and heap churn.

1. Assets/Plugins/WebGL/BrowserBridge.jslib:

JAVASCRIPT
mergeInto(LibraryManager.library, {
  // Fast primitive parameter call (Zero heap allocation)
  JS_ReportPlayerScore: function (levelIndex, score) {
    if (window.onUnityScoreUpdated) {
      window.onUnityScoreUpdated(levelIndex, score);
    }
  },

  // String parameter call (Use only on state changes, never in Update)
  JS_SendTelemetryPayload: function (jsonPtr) {
    var jsonString = UTF8ToString(jsonPtr);
    if (window.dispatchEvent) {
      window.dispatchEvent(
        new CustomEvent("unity-telemetry", { detail: JSON.parse(jsonString) })
      );
    }
  }
});

2. Assets/Scripts/WebGL/BrowserBridge.cs:

CSHARP
using System.Runtime.InteropServices;
using UnityEngine;

namespace MyGame.WebGL
{
    public static class BrowserBridge
    {
#if UNITY_WEBGL && !UNITY_EDITOR
        [DllImport("__Internal")]
        private static extern void JS_ReportPlayerScore(int levelIndex, int score);

        [DllImport("__Internal")]
        private static extern void JS_SendTelemetryPayload(string jsonPayload);
#endif

        public static void ReportScore(int levelIndex, int score)
        {
#if UNITY_WEBGL && !UNITY_EDITOR
            JS_ReportPlayerScore(levelIndex, score);
#else
            Debug.Log($"[WebGL Bridge Stub] Level {levelIndex} Score: {score}");
#endif
        }

        public static void SendTelemetry(string jsonPayload)
        {
#if UNITY_WEBGL && !UNITY_EDITOR
            JS_SendTelemetryPayload(jsonPayload);
#endif
        }
    }
}

8. Browser Compatibility & Deployment Troubleshooting Matrix

Use this diagnostic reference when debugging production WebGL failures across desktop and mobile browsers:

Symptom / Browser ErrorRoot Technical CauseVerified Fix
Unable to parse Build/X.framework.js.br / SyntaxError: Unexpected tokenServer delivered raw Brotli bytes without Content-Encoding: br headerAdd Content-Encoding: br and Content-Type: application/javascript headers on your CDN/server, or enable Decompression Fallback
WebAssembly.instantiateStreaming failed warning in Console.wasm or .wasm.br is served with Content-Type: application/octet-stream instead of application/wasmSet Content-Type: application/wasm on all .wasm and .wasm.br routes
Uncaught RuntimeError: memory access out of bounds / abort(OOM)Wasm linear heap exceeded Maximum Memory Size or browser denied ArrayBuffer reallocationReduce texture resolutions, switch to ASTC/Basis compression, unload unused Addressables before loading new scenes, and set Maximum Memory Size to 2048 MB
iOS Safari reloads the webpage ("A problem repeatedly occurred")Total tab memory (Wasm + GPU VRAM + decoded audio) exceeded iOS Safari's ~1.2 GB–1.5 GB jetsam thresholdClamp config.devicePixelRatio = 1.5, use ASTC texture compression, set Audioclips to Compressed In Memory instead of Decompress On Load
No audio plays until the user clicks a second timeBrowser WebAudio autoplay policy blocks AudioContext creation prior to a trusted DOM click/touch gestureRequire an explicit HTML "Play" button overlay (like WebGLEmbed.tsx) before calling createUnityInstance

Frequently Asked Questions


Need help architecting or optimizing your Unity mobile game? Let's discuss your technical roadmap.

Share this article

Get Practical Unity Development Insights

Technical guides on Unity performance, AI gameplay systems, mobile monetization, and game development.

Unsubscribe at any time. Your data is never shared.

Recommended Reading

More articles in WebGL & Browser Games