| API | Dung lượng | Đặc điểm | Dùng cho |
|---|---|---|---|
localStorage | ~5 MB | Đồng bộ, chỉ chuỗi, còn mãi | Tùy chọn giao diện, nháp nhỏ |
sessionStorage | ~5 MB | Mất khi đóng tab | Trạng thái tạm của tab |
| Cookie | ~4 KB | Gửi kèm mọi request | Phiên đăng nhập (đặt HttpOnly từ server) |
| IndexedDB | Lớn | Bất đồng bộ, lưu object, có index | Dữ liệu offline, cache lớn |
function loadSettings() {
try {
return JSON.parse(localStorage.getItem("settings")) ?? { theme: "light" };
} catch {
return { theme: "light" }; // dữ liệu hỏng hoặc bị chặn (chế độ riêng tư)
}
}
localStorage.setItem("settings", JSON.stringify({ theme: "dark" }));WARNING
Đừng lưu token đăng nhập trong localStorage: bất kỳ script nào chạy trên trang (kể cả qua lỗ hổng XSS) đều đọc được. Ưu tiên cookie HttpOnly; Secure; SameSite.
Dùng cho lazy load, infinite scroll, animation khi cuộn tới — hiệu quả hơn nhiều so với nghe sự kiện scroll:
const observer = new IntersectionObserver((entries) => {
for (const entry of entries) {
if (entry.isIntersecting) {
loadMore();
}
}
}, { rootMargin: "200px" });
observer.observe(document.querySelector("#sentinel"));Tương tự: ResizeObserver (phần tử đổi kích thước), MutationObserver (DOM thay đổi).
// Clipboard
await navigator.clipboard.writeText("MA-GIAM-GIA-2026");
// URL
const url = new URL(location.href);
url.searchParams.set("page", "2");
history.pushState({}, "", url);
// Thông tin thiết bị và tùy chọn người dùng
matchMedia("(prefers-color-scheme: dark)").matches;
const worker = new Worker(new URL("./heavy.js", import.meta.url), { type: "module" });
worker.postMessage({ numbers: bigArray });
worker.onmessage = (e) => console.log("Kết quả:", e.data);self.onmessage = (e) => {
const sum = e.data.numbers.reduce((a, b) => a + b, 0);
self.postMessage(sum);
};Giao diện không bị đứng trong lúc worker tính toán.
Comments