Master Front-End Performance: Load, Run, Build, and Network Optimizations
This article systematically explores front‑end performance optimization across loading, runtime, build, and network stages, offering practical techniques such as resource compression, code splitting, tree shaking, CDN acceleration, render‑blocking reduction, lazy loading, Web Workers, and monitoring tools to dramatically improve page speed and user experience.
Performance optimization is an unavoidable topic for front‑end developers. Slow page loads and interaction lag hurt user experience and can cause user loss. This article reviews optimization methods across four stages—"load, run, build, network"—to help improve front‑end performance.
Load performance optimization: faster first screen
The goal of the loading phase is to "display visible content to users as quickly as possible", reducing white‑screen and first‑screen waiting time.
Resource compression and code obfuscation
The core goal of "resource compression" is to make files as small as possible for faster browser transmission and parsing.
Code compression : remove spaces and comments from HTML, CSS, JS and shorten variable names. Build tools like Vite or Webpack with plugins such as Terser handle this automatically.
Image optimization : use high‑compression formats like WebP or AVIF and tools like imagemin , tinypng . For many small icons, combine them into CSS sprites to reduce HTTP requests.
Code Splitting
Code splitting divides project code into smaller files by feature or page, loading only the parts needed for the current route.
import React, { Suspense } from 'react';
const Chart = React.lazy(() => import('./Chart'));
function App() {
return (
<Suspense fallback={<div>Loading...</div>}>
<Chart />
</Suspense>
);
} const routes = [
{ path: '/', component: () => import('@/views/Home.vue') },
{ path: '/about', component: () => import('@/views/About.vue') }
];Tree Shaking
Tree shaking automatically removes unused code during bundling, making the final file smaller and faster. It relies on the static structure of ES Modules ( import / export) to determine which code is actually used.
In Vite (based on Rollup) and most modern bundlers, tree shaking is enabled by default for production builds. To benefit, use ES Module syntax instead of require and avoid global side‑effects, or declare { "sideEffects": false } in package.json.
{ "sideEffects": false }CDN acceleration
CDN acceleration distributes static assets (JS, CSS, images, fonts) to multiple global nodes, allowing users to fetch resources from the nearest server, reducing latency and improving load speed.
Reduce render‑blocking
Render‑blocking occurs when the browser pauses HTML parsing to load resources like CSS or synchronous JS. Reducing it means presenting critical content first and loading non‑critical resources later or asynchronously.
CSS optimization : inline critical CSS for the first screen, load other stylesheets with media attributes or delayed loading.
<link rel="stylesheet" href="style.css" media="print" onload="this.media='all'">JS optimization : add defer or async to non‑essential scripts to avoid blocking HTML parsing.
<script src="app.js" defer></script>
<script src="analytics.js" async></script>Font loading optimization : use font-display: swap so text renders with a fallback system font while the custom font loads.
@font-face {
font-family: 'MyFont';
src: url('myfont.woff2') format('woff2');
font-display: swap;
}Preload and prefetch
Preload and prefetch aim to prepare resources or pages in advance so users experience almost no wait when navigating.
preload : load key resources (fonts, CSS, first‑screen images) early.
<link rel="preload" href="/fonts/main.woff2" as="font" type="font/woff2" crossorigin>prefetch : use idle time to load resources that might be needed later (e.g., next page JS).
<link rel="prefetch" href="/next-page.js">SSR and SSG
Both approaches generate HTML before the user request arrives, reducing white‑screen time.
SSR (Server‑Side Rendering) : the server renders HTML in real time; suitable for dynamic data scenarios. In React, next.js provides SSR.
SSG (Static Site Generation) : static HTML files are generated at build time; ideal for content that changes infrequently, such as blogs or documentation. Tools include Astro, Next.js SSG mode, VitePress, VuePress.
Gzip/Brotli compression
Enabling Gzip or Brotli on the server significantly reduces the size of text resources (JS, CSS, HTML), often cutting network transfer by 60‑80%.
Dependency sharing
In multi‑page applications or micro‑frontends, extracting common dependencies (e.g., React, Vue, Lodash) for browser cache or CDN sharing reduces duplicate downloads and improves first‑screen load.
// Vite Rollup split configuration
export default {
build: {
rollupOptions: {
output: {
manualChunks: {
react: ['react', 'react-dom'], // split React
lodash: ['lodash'] // split Lodash
}
}
}
}
} // React dynamic import
const Chart = React.lazy(() => import('./Chart'));
export default function Page() {
return (
<React.Suspense fallback={<div>Loading...</div>}>
<Chart />
</React.Suspense>
);
} // Vite exclude dependency
export default {
build: {
rollupOptions: {
external: ['vue'] // exclude Vue from bundle
}
}
}Runtime optimization
The goal of the runtime phase is to keep the page smooth and responsive during interaction by optimizing rendering strategies and code.
Avoid unnecessary reflow and repaint
Reflow : occurs when element size, position, or layout changes, forcing the browser to recalculate layout.
Repaint : occurs when only visual styles change without layout changes.
Virtual scroll / list
Rendering a large table (e.g., 10,000 rows) all at once will freeze the browser. Virtual lists render only the visible portion and replace DOM nodes on scroll, keeping DOM count stable. Vue and React have many libraries for this.
Debounce and throttle
Both techniques optimize high‑frequency events but differ in behavior.
Debounce : after the last event, wait a specified time before executing the callback. If another event occurs during the wait, the timer resets. Suitable for search input, window resize, real‑time validation.
Throttle : ensures the callback runs at most once per fixed interval, regardless of how many events fire. Suitable for scroll, drag, mousemove.
Image lazy loading
Load only images in the viewport initially; other images load when scrolled into view, reducing first‑screen load time, network requests, and server pressure.
<img src="image.jpg" loading="lazy" alt="example" />Libraries such as react-lazyload and vue-lazyload provide convenient wrappers.
Web Worker offloading
JavaScript runs on a single thread; heavy computations block UI rendering. Web Workers create a separate thread to run such tasks, keeping the UI responsive.
self.onmessage = e => {
let sum = 0;
for (let i = 0; i < e.data; i++) sum += i;
self.postMessage(sum);
}; import React from 'react';
export default function App() {
const runWorker = () => {
const worker = new Worker(new URL('./worker.js', import.meta.url));
worker.postMessage(1e8); // compute 100 million iterations
worker.onmessage = e => {
alert(`Result: ${e.data}`);
worker.terminate();
};
};
return <button onClick={runWorker}>Start Calculation</button>;
}Memory leak monitoring and optimization
Memory leaks cause pages to become slower over time and eventually crash. Common causes include uncleared timers/events, retained DOM nodes, and closures holding unnecessary variables.
Use Chrome Performance to capture memory snapshots.
Clean up resources in component unmount: React useEffect cleanup, Vue beforeUnmount.
Build optimization
Compression and obfuscation
In React/Vue projects, compression and obfuscation are usually handled automatically by the build tool; manual configuration is rarely needed.
Third‑party library optimization
Package splitting strategy
Split the bundled code into multiple chunks to avoid loading everything at once, improving first‑screen speed. Common strategies include route‑based splitting, component‑based splitting, and dependency‑based splitting.
// Vite Rollup split configuration
export default {
build: {
rollupOptions: {
output: {
manualChunks: {
react: ['react', 'react-dom'], // split React
lodash: ['lodash'] // split Lodash
}
}
}
}
}Lazy load third‑party resources
Similar to route lazy loading, defer loading of non‑critical third‑party libraries until needed.
// React dynamic import
const Chart = React.lazy(() => import('./Chart'));
export default function Page() {
return (
<React.Suspense fallback={<div>Loading...</div>}>
<Chart />
</React.Suspense>
);
}Dependency exclusion
Exclude certain dependencies from the bundle and load them via CDN to reduce bundle size.
// Vite config
export default {
build: {
rollupOptions: {
external: ['vue'] // exclude Vue
}
}
}Network optimization
TCP pre‑connect
Establish TCP + TLS connections to target servers in advance to reduce request latency.
<link rel="preconnect" href="https://cdn.example.com">DNS pre‑fetch
Resolve domain names early to cut DNS lookup delay.
<link rel="dns-prefetch" href="//cdn.example.com">Request merging
Combine duplicate requests; front‑end can debounce or check request status to avoid redundant calls.
import { ref } from 'vue';
import axios from 'axios';
const timeoutId = ref(null);
function debounce(fn, delay) {
return function(...args) {
if (timeoutId.value) clearTimeout(timeoutId.value);
timeoutId.value = setTimeout(() => fn(...args), delay);
};
}
function fetchData() {
axios.get('http://api/gcshi')
.then(response => console.log(response.data));
}
const debouncedFetchData = debounce(fetchData, 300);How to view web performance
Browser built‑in tools
Network panel : inspect request timing, size, cache hits, identify large or slow resources.
Performance panel : metrics such as FCP, LCP, CLS, TTI.
Lighthouse panel : automated audit of performance, accessibility, SEO, with suggestions.
Third‑party tools
WebPageTest (https://www.webpagetest.org/) simulates different regions and network conditions, showing waterfall charts and render timelines.
GTmetrix (https://gtmetrix.com/) provides detailed reports, first‑screen screenshots, and video playback for before‑after comparisons.
Performance monitoring and reporting
Sentry : captures performance metrics, JS errors, slow API calls.
Alibaba Cloud ARMS / ByteDance Volcano : supports front‑end and back‑end tracing.
Custom telemetry : use the Performance API to report metrics to a logging system.
Conclusion
This article outlines common front‑end performance optimization techniques; feel free to add any missing strategies.
Rare Earth Juejin Tech Community
Juejin, a tech community that helps developers grow.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
