跪拜 Guibai
← Back to the summary

Slash Electron Idle Memory from 500MB to 163MB with Lazy WebView Mounting and esbuild Minification

The quickest way to get criticized for building an Electron desktop app is the old "a shell that eats 1GB of memory" complaint.

Recently I was working on a local AI workbench (with both a local chat/code diff panel and several separate creation and browsing split screens embedded via <webview>). When I ran the first version and opened Task Manager, I couldn't hold it together: after clicking through two or three tabs and switching back to an idle page, the multi-process total sat at a solid 480MB–550MB, and the main process bundle main.cjs had ballooned to 483 KB.

After that I spent two days making three cuts, bringing the total idle memory of the four core processes down to 163.3 MB and main.cjs down to 295.7 KB, while tab switching actually felt more responsive. These three real changes that you can copy directly into your project are recorded below, for those building multi-WebView Electron apps.


1. Core metric comparison before and after

Here are the conclusions first (environment: macOS Apple Silicon, Electron 35.7.5, measured after opening the workbench, switching through 3 built-in WebView tabs, and then idling):

Observed metric Before optimization After optimization Change method
Idle total memory (main + renderer + GPU + WebView) ~480–550 MB 163.3 MB <webview> deferred mounting + background timer sleep and reclaim
Main process main.cjs size 483 KB 295.7 KB esbuild --minify --legal-comments=none
preload.cjs / boot.cjs size ~18 KB 5.8 KB / 1.9 KB Streamlined bridge + enforced zero sourcemaps
Heavy Tab first-frame jank occasional 120ms frame drops click-to-highlight immediately requestAnimationFrame delayed mount by 1 frame

electron_163mb_memory.jpg


2. First cut: <webview> delayed mounting by 1 frame + auto sleep and reclaim after 10 minutes in background

The biggest memory hog in multi-tab Electron apps is often not your own React UI, but the <webview> renderer processes hiding behind display: none that you haven't looked at for half an hour. Each resident <webview> can easily eat 100MB–250MB.

But you also can't destroy the webview one second after switching away, or users will get a white-screen reload every time they switch back and forth between two tabs. The compromise we finally put in place is three layers of guardrails:

  1. On-demand + delayed mounting by 1 frame: when clicking a heavy Web tab, first let React complete the tab highlight painting, then on the next frame (requestAnimationFrame) insert the tab into mountedWebTabs, eliminating the visual jank at the moment of click.
  2. Default 10-minute background auto-reclaim: hidden <webview>s that haven't been viewed for more than 10 minutes are removed from mountedWebTabs, letting Chromium actually reclaim the corresponding renderer process memory.
  3. A "low memory mode" toggle: after enabling it on memory-constrained machines, switching away from a Web tab reclaims it immediately, only keeping the current page alive.

The core implementation is very clean, directly a reusable React Hook:

const WEB_TABS = [
  { id: 'canvas' },
  { id: 'image' },
  { id: 'video' },
] as const;

// 1. When switching tabs, delay mounting by 1 frame to avoid click-highlight frame drops
function handleSelectTab(tab: string, isWebTab: boolean) {
  setActiveTab(tab);
  if (isWebTab && !mountedWebTabs.has(tab)) {
    window.requestAnimationFrame(() => {
      setMountedWebTabs((prev) => {
        if (prev.has(tab)) return prev;
        const next = new Set(prev);
        next.add(tab);
        return next;
      });
    });
  }
}

// 2. Memory guard: low memory mode releases on switch-away; default auto-reclaims after 10 minutes idle in background
useEffect(() => {
  const isActiveWebTab = WEB_TABS.some((wt) => wt.id === activeTab);

  if (settings?.lowMemoryWebviews) {
    setMountedWebTabs((prev) => {
      const next = isActiveWebTab ? new Set([activeTab]) : new Set<string>();
      if (prev.size === next.size && [...prev].every((k) => next.has(k))) return prev;
      return next;
    });
    return;
  }

  const hiddenTabs = [...mountedWebTabs].filter((id) => id !== activeTab);
  if (hiddenTabs.length === 0) return;

  const timer = window.setTimeout(() => {
    setMountedWebTabs((prev) => {
      let changed = false;
      const next = new Set<string>();
      for (const id of prev) {
        if (id === activeTab) next.add(id);
        else changed = true;
      }
      return changed ? next : prev;
    });
  }, 10 * 60 * 1000);

  return () => window.clearTimeout(timer);
}, [activeTab, mountedWebTabs, settings?.lowMemoryWebviews]);

This cut had the most obvious effect: after leaving three pages in the background for 10 minutes, the process count directly converged back to 4, and total memory dropped from 500MB to about 163MB.


3. Second cut: esbuild lightweight compression, resolutely avoiding heavy obfuscation shells

I also slimmed down the build commands for the 4 Electron-side entry files (boot / main / preload / webview-preload), while explicitly locking sourcemap: false in vite.config.ts and filtering .map / .DS_Store in the packaging script:

{
  "scripts": {
    "build:electron": "esbuild electron/boot.ts --bundle --platform=node --format=cjs --minify --legal-comments=none --outfile=dist-electron/boot.cjs --external:electron && esbuild electron/main.ts --bundle --platform=node --format=cjs --minify --legal-comments=none --outfile=dist-electron/main.cjs --external:electron && esbuild electron/preload.ts --bundle --platform=node --format=cjs --minify --legal-comments=none --outfile=dist-electron/preload.cjs --external:electron && esbuild electron/webview-preload.ts --bundle --platform=node --format=cjs --minify --legal-comments=none --outfile=dist-electron/webview-preload.cjs --external:electron"
  }
}

While I'm here, I'll share a pitfall that's easy to trip on: don't wrap the Electron main process in a heavy obfuscation shell (like javascript-obfuscator or V8 bytecode wrapping) just for "anti-reversing". The reasons are practical:


4. Third cut: build process memory monitoring and "preserve login, clear cache" directly into the settings page

Just looking at DevTools on your own dev machine isn't enough; real users' machines vary wildly. In the main process we use app.getAppMetrics() to aggregate each process's (Browser / Tab / GPU / Utility) workingSetSize into a real-time memory diagnostic card, and also provide a "One-click clear cache (preserve login Cookie)" button:

import { app, session } from 'electron';

export function getProcessMemorySnapshot() {
  const metrics = app.getAppMetrics();
  let totalKb = 0;
  const breakdown = metrics.map((m) => {
    const kb = m.memory?.workingSetSize ?? 0;
    totalKb += kb;
    return { pid: m.pid, type: m.type, mb: Number((kb / 1024).toFixed(1)) };
  });
  return { totalMb: Number((totalKb / 1024).toFixed(1)), processCount: metrics.length, breakdown };
}

// Only clear HTTP disk/memory cache, never call clearStorageData and accidentally damage user login Cookie
export async function clearWebCachesPreserveAuth() {
  await session.defaultSession.clearCache();
  await session.fromPartition('persist:studio').clearCache();
}

Key point: use clearCache() instead of clearStorageData(), so clicking it cleans image/script caches thoroughly while user login state and localStorage remain completely untouched.


Summary

The real memory culprits in Electron are mostly runaway background <webview>s and unmanaged resident renderer processes. Once you do the dirty work of delayed mounting + background idle reclaim + clearCache() partition cleanup + standard esbuild compression, the desktop side can be both lightweight and responsive.

What other low-memory or anti-black-screen / anti-flicker tricks do you use in your Electron / Tauri apps? Feel free to leave a comment below; let's copy homework from each other.

Comments

Top 2 from juejin.cn, machine-translated. The original thread is authoritative.

小小楠

Just use Tauri.

去吧波波鸟

The 10-minute figure is interesting. Too short and it gets annoying switching back and forth, too long and it just sits there wasting memory. I'll note that the cache clearing deliberately avoids clearStorageData, because getting logged out is a real pain.