Skip to main content
Performance 4 mins read Devs2.org

Web Performance Optimization - 10 Kỹ Thuật Tăng Tốc Độ Website Năm 2026

Khám phá 10 kỹ thuật tối ưu hiệu suất web hàng đầu giúp website của bạn tải nhanh hơn, trải nghiệm người dùng tốt hơn và xếp hạng SEO cao hơn.

#Performance #Web Development #Optimization #Core Web Vitals #Frontend #SEO

Bạn có biết rằng 53% người dùng rời khỏi trang web nếu nó tải quá 3 giây? Và mỗi giây trễ thêm làm giảm conversions khoảng 7%. Trong thế giới cạnh tranh ngày nay, tốc độ không còn là tùy chọn — đó là yêu cầu sống còn.

Trong hướng dẫn này, chúng ta sẽ khám phá 10 kỹ thuật tối ưu hiệu suất web được sử dụng bởi các công ty lớn nhất thế giới, từ cơ bản đến nâng cao.

web-performance-optimization-complete-guide

1. Image Optimization — Tối Ưu Hóa Hình Ảnh

Hình ảnh thường chiếm 50-70% tổng dung lượng trang web. Tối ưu hóa hình ảnh là bước đầu tiên và hiệu quả nhất.

Sử Dụng Định Dạng Hiện Đại

<!-- Thay vì JPEG/PNG truyền thống -->
<picture>
  <source srcset="hero.avif" type="image/avif">
  <source srcset="hero.webp" type="image/webp">
  <img src="hero.jpg" alt="Hero image" loading="lazy">
</picture>

AVIF và WebP nhỏ hơn JPEG/PNG 30-70% mà vẫn giữ chất lượng tương đương.

Responsive Images

<img 
  src="photo-800w.jpg"
  srcset="photo-400w.jpg 400w,
          photo-800w.jpg 800w,
          photo-1200w.jpg 1200w"
  sizes="(max-width: 600px) 400px,
         (max-width: 1024px) 800px,
         1200px"
  alt="Responsive photo"
>

Trình duyệt sẽ tự động tải kích thước phù hợp với màn hình người dùng.

Lazy Loading Native

<!-- Tải khi cuộn đến gần -->
<img src="below-fold.jpg" loading="lazy" alt="Below fold image">

<!-- Prefetch hình ảnh quan trọng ở cuối trang -->
<link rel="prefetch" href="next-page-hero.jpg" as="image">

2. Code Splitting — Chia Nhỏ Mã Nguồn

Thay vì tải toàn bộ ứng dụng cùng lúc, hãy chia nhỏ theo route hoặc tính năng.

Với JavaScript Bundlers

// Dynamic import — chỉ load khi cần
const Dashboard = () => import('./pages/Dashboard');
const Settings = () => import('./pages/Settings');

// Route-based code splitting
const routes = [
  { path: '/dashboard', component: Dashboard },
  { path: '/settings', component: Settings },
];

Với React.lazy

import { lazy, Suspense } from 'react';

const HeavyChart = lazy(() => import('./components/HeavyChart'));
const DataGrid = lazy(() => import('./components/DataGrid'));

function App() {
  return (
    <Suspense fallback={<LoadingSpinner />}>
      <HeavyChart data={chartData} />
      <DataGrid items={items} />
    </Suspense>
  );
}

Kết quả: Trang ban đầu chỉ tải ~50KB thay vì ~500KB.

3. Tree Shaking — Loại Bỏ Code Không Dùng

Tree shaking loại bỏ code dead-code từ các thư viện bạn import.

// ❌ Import toàn bộ thư viện
import _ from 'lodash';
_.debounce(fn, 300);
_.throttle(fn, 300);

// ✅ Import từng hàm (tree shaking hoạt động)
import debounce from 'lodash/debounce';
import throttle from 'lodash/throttle';

Với Vite hoặc Webpack, tree shaking tự động hoạt động khi build production. Đảm bảo package.json có field "sideEffects": false.

4. Caching Strategy — Chiến Lược Cache Thông Minh

Cache đúng cách giúp trả về nội dung gần như tức thì.

Service Worker Cache

// sw.js — Cache-first cho tài nguyên tĩnh
self.addEventListener('fetch', (event) => {
  if (event.request.url.match(/\.(js|css|png|jpg|woff2)$/)) {
    event.respondWith(
      caches.match(event.request).then((cached) => {
        return cached || fetch(event.request).then((response) => {
          // Lưu vào cache cho lần sau
          const clone = response.clone();
          caches.open('v1').then((cache) => cache.put(event.request, clone));
          return response;
        });
      })
    );
  }
});

HTTP Cache Headers

# Nginx configuration
location ~* \.(js|css|png|jpg|svg|woff2)$ {
  expires 1y;
  add_header Cache-Control "public, immutable";
}

location /api/ {
  expires -1;
  add_header Cache-Control "no-cache, no-store, must-revalidate";
}

Quy tắc vàng: Tài nguyên tĩnh → cache dài hạn với hash tên file. API responses → không cache hoặc cache ngắn.

5. Minification & Compression — Nén Mã Nguồn

Minify CSS, JS, HTML

# CSS minification
npx cssnano input.css -o output.min.css

# JS minification (Vite tự động làm khi build)
# production build tự minify + compress

# HTML minification
npx html-minifier-terser --input index.html --output dist/index.html

Enable Brotli/Gzip Compression

server {
  # Brotli (ưu tiên)
  brotli on;
  brotli_comp_level 6;
  brotli_types text/plain text/css application/json application/javascript;

  # Fallback Gzip
  gzip on;
  gzip_comp_level 5;
  gzip_types text/plain text/css application/json application/javascript;
}

6. Critical CSS — CSS Quan Trọng Inline

Chỉ chèn CSS cần thiết cho phần trên cùng (above-the-fold) trực tiếp vào HTML, phần còn lại load async.

<!DOCTYPE html>
<html>
<head>
  <!-- Critical CSS inline -->
  <style>
    .header { position: fixed; top: 0; width: 100%; }
    .hero { height: 100vh; display: flex; align-items: center; }
    .hero-title { font-size: 3rem; color: #1a1a2e; }
  </style>
  
  <!-- Non-critical CSS load async -->
  <link rel="stylesheet" href="styles.css" media="print" onload="this.media='all'">
  <noscript><link rel="stylesheet" href="styles.css"></noscript>
</head>
<body>
  <!-- Content -->
</body>
</html>

Công cụ tự động extract critical CSS: Critical hoặc gulp-critical-css.

7. Font Optimization — Tối Ưu Font Chữ

Font chữ custom có thể làm chậm rendering đáng kể.

Sử Dụng font-display: swap

@font-face {
  font-family: 'CustomFont';
  src: url('/fonts/custom.woff2') format('woff2');
  font-display: swap; /* Hiển thị font hệ thống trước */
  font-weight: 400;
  font-style: normal;
}

Preload Font Quan Trọng

<link rel="preload" href="/fonts/custom.woff2" as="font" type="font/woff2" crossorigin>

Giới Hạn Số Font Weight

Thay vì load 7 weight (100-900), chỉ load những weight thực sự dùng:

/* Chỉ load Regular và Bold */
@font-face { font-family: 'Inter'; src: url('inter-regular.woff2'); font-weight: 400; }
@font-face { font-family: 'Inter'; src: url('inter-bold.woff2'); font-weight: 700; }

8. Reduce Third-Party Scripts — Giảm Script Bên Thứ Ba

Mỗi third-party script thêm 200-500ms vào thời gian tải.

Deferred Loading

<!-- Load sau khi page render xong -->
<script defer src="https://analytics.example.com/tracker.js"></script>

<!-- Hoặc load bằng Intersection Observer (chỉ khi user scroll đến) -->
<script>
  const observer = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        const script = document.createElement('script');
        script.src = 'https://chat.example.com/widget.js';
        document.body.appendChild(script);
        observer.disconnect();
      }
    });
  });
  observer.observe(document.getElementById('chat-container'));
</script>

Self-Host Quan Trọng

Thay vì nhúng từ CDN bên ngoài, self-host những script quan trọng:

<!-- ❌ Chậm: phụ thuộc vào CDN bên thứ ba -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<!-- ✅ Nhanh: self-hosted -->
<script src="/js/chart.min.js"></script>

9. Server-Side Optimization — Tối Ưu Phía Server

Sử Dụng Edge Computing

// Next.js Edge Middleware
export function middleware(request) {
  const cacheKey = request.url;
  
  // Check edge cache trước
  const cached = await caches.default.match(cacheKey);
  if (cached) return cached;
  
  // Fallback: serve static version
  return new Response('<h1>Loading...</h1>', {
    headers: { 'Cache-Control': 'public, max-age=60' }
  });
}

export const config = {
  matcher: ['/products/:path*', '/blog/:path*'],
};

Database Query Optimization

-- ❌ Slow query: SELECT * lấy tất cả cột
SELECT * FROM products WHERE category_id = 5;

-- ✅ Fast query: chỉ lấy cột cần thiết + index
SELECT id, name, price, image_url 
FROM products 
WHERE category_id = 5
ORDER BY created_at DESC
LIMIT 20;
// ❌ N+1 problem
const users = await User.findAll();
users.forEach(user => {
  user.posts = await Post.findAll({ where: { userId: user.id } });
});

// ✅ Single query với include/join
const users = await User.findAll({
  include: [{ model: Post, attributes: ['id', 'title'] }],
  limit: 20
});

10. Monitor & Measure — Giám Sát Liên Tục

Bạn không thể cải thiện thứ gì bạn không đo lường được.

Real User Monitoring (RUM)

// Gửi metrics thực tế từ người dùng
window.addEventListener('load', () => {
  const perf = performance.getEntriesByType('navigation')[0];
  
  navigator.sendBeacon('/api/metrics', JSON.stringify({
    lcp: perf.loadEventEnd - perf.startTime,
    fcp: performance.getEntriesByName('first-contentful-paint')[0].startTime,
    url: window.location.href,
    device: navigator.userAgent
  }));
});

Công Cụ Kiểm Tra Hiệu Suất

Công cụMục đíchLink
LighthouseAudit toàn diệnchrome://inspect
WebPageTestPhân tích chi tiếtwebpagetest.org
PageSpeed InsightsĐiểm Googlepagespeed.web.dev
Chrome DevTools NetworkDebug networkF12 → Network
SpeedcurveRUM continuousspeedcurve.com

Tổng Kết: Checklist Tối Ưu Hiệu Suất

Dưới đây là checklist nhanh bạn có thể áp dụng ngay:

#Hành ĐộngĐộ khóTác động
1Compress & convert images sang AVIF/WebPDễ⭐⭐⭐⭐⭐
2Enable lazy loading cho imagesDễ⭐⭐⭐⭐
3Minify CSS/JS/HTMLDễ⭐⭐⭐
4Enable Brotli compressionTrung bình⭐⭐⭐⭐
5Implement code splittingTrung bình⭐⭐⭐⭐⭐
6Setup proper caching headersTrung bình⭐⭐⭐⭐
7Extract critical CSSTrung bình⭐⭐⭐
8Optimize fonts (swap + preload)Dễ⭐⭐⭐
9Reduce third-party scriptsKhó⭐⭐⭐⭐⭐
10Set up monitoring (Lighthouse CI)Trung bình⭐⭐⭐⭐

Hiệu suất không phải là điểm đến — đó là hành trình liên tục. Bắt đầu với 3-4 kỹ thuật dễ nhất, đo lường kết quả, rồi dần dần áp dụng những kỹ thuật phức tạp hơn.

Website của bạn đang gặp vấn đề hiệu suất nào? Hãy kiểm tra bằng Lighthouse ngay hôm nay và bắt đầu cải thiện!


Bạn đã áp dụng kỹ thuật nào trong số này chưa? Chia sẻ kết quả cải thiện tốc độ của bạn trong phần bình luận!

Recently Used Tools