01现代 Web 能力地图
浏览器早已不只是「显示文档」的工具,它运行着一个完整的应用平台。下面这张表可以帮你建立整体认知,知道遇到什么需求该找什么 API。
| 能力 | 技术 | 典型场景 |
|---|---|---|
| 2D 绘图 | Canvas 2D | 图表、粒子、签名板、图片处理 |
| 3D 渲染 | WebGL / WebGPU | 3D 产品展示、数据可视化 |
| 高级视觉 | CSS filter / clip-path / 3D | 毛玻璃、异形裁切、卡片翻转 |
| 组件化 | Web Components | 跨框架复用组件 |
| 懒加载 | IntersectionObserver | 图片懒加载、滚动动画 |
| 离屏计算 | Web Worker | 大数据处理、加解密 |
| 离线能力 | Service Worker + Cache | PWA、离线可用 |
| 本地存储 | localStorage / IndexedDB | 偏好设置、离线数据 |
| 实时通信 | WebSocket / SSE | 聊天、实时通知 |
| 图形交互 | Pointer Events / Drag & Drop | 拖拽排序、画板 |
02Canvas 2D:逐像素的绘画
Canvas 是一块位图画布。它本身不保存图形对象,你调用绘图 API 后,像素就被「画死」在画布上,想要更新必须清空重绘。这正是动画的基础。
第一步:坐标系统与基础图形
const canvas = document.querySelector('#myCanvas');
const ctx = canvas.getContext('2d');
// 处理高分屏模糊:按设备像素比放大画布
const dpr = window.devicePixelRatio || 1;
canvas.width = 600 * dpr;
canvas.height = 400 * dpr;
canvas.style.width = '600px';
canvas.style.height = '400px';
ctx.scale(dpr, dpr);
// 画一个矩形
ctx.fillStyle = 'rgba(111, 143, 122, 0.18)';
ctx.fillRect(20, 20, 200, 120);
// 描边
ctx.strokeStyle = '#4c6b57';
ctx.lineWidth = 2;
ctx.strokeRect(20, 20, 200, 120);
// 画一条路径:圆
ctx.beginPath();
ctx.arc(320, 100, 50, 0, Math.PI * 2);
ctx.fillStyle = '#c9a86a';
ctx.fill();
ctx.stroke();
// 画文字
ctx.font = '600 18px "Songti SC", serif';
ctx.fillStyle = '#33302b';
ctx.fillText('山中笔记', 40, 200);
// 画线
ctx.beginPath();
ctx.moveTo(40, 240);
ctx.lineTo(360, 240);
ctx.strokeStyle = 'rgba(76, 107, 87, 0.3)';
ctx.setLineDash([6, 6]);
ctx.stroke();
ctx.setLineDash([]);
动画循环:清空 → 更新 → 绘制
const canvas = document.querySelector('#particleCanvas');
const ctx = canvas.getContext('2d');
let width, height;
const particles = [];
function resize() {
const dpr = window.devicePixelRatio || 1;
const rect = canvas.getBoundingClientRect();
width = rect.width;
height = rect.height;
canvas.width = width * dpr;
canvas.height = height * dpr;
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
}
function createParticles(count = 60) {
particles.length = 0;
for (let i = 0; i < count; i++) {
particles.push({
x: Math.random() * width,
y: Math.random() * height,
vx: (Math.random() - 0.5) * 0.6,
vy: (Math.random() - 0.5) * 0.6,
r: Math.random() * 2.2 + 1
});
}
}
function draw() {
ctx.clearRect(0, 0, width, height);
// 连接距离较近的点,形成「星座」效果
for (let i = 0; i < particles.length; i++) {
for (let j = i + 1; j < particles.length; j++) {
const dx = particles[i].x - particles[j].x;
const dy = particles[i].y - particles[j].y;
const dist = Math.hypot(dx, dy);
if (dist < 110) {
ctx.beginPath();
ctx.moveTo(particles[i].x, particles[i].y);
ctx.lineTo(particles[j].x, particles[j].y);
ctx.strokeStyle = `rgba(111,143,122,${(1 - dist / 110) * 0.28})`;
ctx.lineWidth = 1;
ctx.stroke();
}
}
}
// 更新并绘制粒子
particles.forEach(p => {
p.x += p.vx;
p.y += p.vy;
// 边界反弹
if (p.x < 0 || p.x > width) p.vx *= -1;
if (p.y < 0 || p.y > height) p.vy *= -1;
ctx.beginPath();
ctx.arc(p.x, p.y, p.r, 0, Math.PI * 2);
ctx.fillStyle = 'rgba(76,107,87,0.5)';
ctx.fill();
});
requestAnimationFrame(draw);
}
window.addEventListener('resize', () => {
resize();
createParticles();
});
resize();
createParticles();
requestAnimationFrame(draw);
性能要点:离屏画布(OffscreenCanvas)可以把绘制移到 Worker;大量静态图形可先画到离屏 canvas,再一次性 drawImage;避免在每帧里创建新对象与过长的路径。
图片处理与导出
const img = new Image();
img.crossOrigin = 'anonymous'; // 处理跨域图片导出时的画布污染
img.src = 'photo.jpg';
img.onload = () => {
ctx.drawImage(img, 0, 0, 400, 300);
// 读取像素,做灰度处理
const imageData = ctx.getImageData(0, 0, 400, 300);
const data = imageData.data;
for (let i = 0; i < data.length; i += 4) {
const gray = data[i] * 0.299 + data[i + 1] * 0.587 + data[i + 2] * 0.114;
data[i] = data[i + 1] = data[i + 2] = gray;
}
ctx.putImageData(imageData, 0, 0);
// 导出为图片
const url = canvas.toDataURL('image/png');
document.querySelector('#download').href = url;
};
03WebGL:让浏览器跑起 3D
WebGL 基于 OpenGL ES,直接操作 GPU。它的概念比 Canvas 2D 陡峭得多:着色器、缓冲区、矩阵变换。实际项目中通常借助 Three.js 等库,但理解底层流程很有帮助。
const gl = canvas.getContext('webgl');
if (!gl) throw new Error('当前浏览器不支持 WebGL');
// 1. 编写着色器(GLSL)
const vertexSource = `
attribute vec2 position;
void main() {
gl_Position = vec4(position, 0.0, 1.0);
}
`;
const fragmentSource = `
precision mediump float;
uniform vec4 color;
void main() {
gl_FragColor = color;
}
`;
// 2. 编译并链接成 program
function createShader(type, source) {
const shader = gl.createShader(type);
gl.shaderSource(shader, source);
gl.compileShader(shader);
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
throw new Error(gl.getShaderInfoLog(shader));
}
return shader;
}
const program = gl.createProgram();
gl.attachShader(program, createShader(gl.VERTEX_SHADER, vertexSource));
gl.attachShader(program, createShader(gl.FRAGMENT_SHADER, fragmentSource));
gl.linkProgram(program);
gl.useProgram(program);
// 3. 传入顶点数据
const buffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
-0.5, -0.5,
0.5, -0.5,
0.0, 0.5
]), gl.STATIC_DRAW);
const position = gl.getAttribLocation(program, 'position');
gl.enableVertexAttribArray(position);
gl.vertexAttribPointer(position, 2, gl.FLOAT, false, 0, 0);
// 4. 设置颜色并绘制
gl.uniform4f(gl.getUniformLocation(program, 'color'), 0.42, 0.56, 0.48, 1.0);
gl.clearColor(0.98, 0.97, 0.94, 1.0);
gl.clear(gl.COLOR_BUFFER_BIT);
gl.drawArrays(gl.TRIANGLES, 0, 3);
什么时候用 WebGL?需要大量实时图形、3D 场景、复杂粒子或 GPU 并行计算时。如果只是图表或简单 2D 动画,Canvas 2D 甚至 SVG 会更简单、更易维护。
04CSS 高级视觉:少写 JS 多出效果
现代 CSS 已经能独立完成很多过去必须依赖 JavaScript 的视觉与交互效果。下面这些技巧能让页面质感明显提升。
/* 1. 毛玻璃:半透明背景 + 背景模糊 */
.glass {
background: rgba(255, 253, 248, 0.72);
backdrop-filter: blur(14px) saturate(1.4);
-webkit-backdrop-filter: blur(14px) saturate(1.4);
border: 1px solid rgba(255, 255, 255, 0.6);
}
/* 2. 异形裁切 */
.blob {
clip-path: polygon(50% 0%, 90% 20%, 100% 60%, 75% 100%, 25% 100%, 0% 60%, 10% 20%);
}
/* 也可以使用 ellipse、circle、path() */
/* 3. 3D 翻转卡片 */
.flip-card { perspective: 900px; }
.flip-inner {
position: relative;
transform-style: preserve-3d;
transition: transform 0.7s cubic-bezier(0.22, 0.61, 0.36, 1);
}
.flip-card:hover .flip-inner { transform: rotateY(180deg); }
.flip-face {
backface-visibility: hidden;
position: absolute;
inset: 0;
}
.flip-back { transform: rotateY(180deg); }
/* 4. 渐变文字 */
.gradient-text {
background: linear-gradient(120deg, #4c6b57, #c9a86a 60%, #a3716d);
-webkit-background-clip: text;
background-clip: text;
color: transparent;
}
/* 5. 遮罩:图片渐隐 */
.fade-img {
mask-image: linear-gradient(to bottom, #000 60%, transparent);
-webkit-mask-image: linear-gradient(to bottom, #000 60%, transparent);
}
/* 6. 混合模式:让叠层更有质感 */
.overlay {
mix-blend-mode: multiply;
opacity: 0.85;
}
/* 7. 滚动驱动动画(渐进增强) */
@keyframes grow {
from { transform: scaleX(0); }
to { transform: scaleX(1); }
}
.scroll-progress {
transform-origin: left;
animation: grow linear both;
animation-timeline: scroll(root block);
}
05Web Components:原生组件化
Web Components 由三项技术组成:Custom Elements(自定义标签)、Shadow DOM(样式与结构隔离)、HTML Templates(可复用模板)。它不依赖任何框架。
class NoteCard extends HTMLElement {
// 声明需要监听的属性,变化时触发 attributeChangedCallback
static get observedAttributes() {
return ['title', 'date'];
}
constructor() {
super();
// 1. 附加 Shadow DOM,内部样式不会泄漏到外部
const shadow = this.attachShadow({ mode: 'open' });
// 2. 定义模板
shadow.innerHTML = `
<style>
:host {
display: block;
max-width: 420px;
padding: 24px;
background: #fffdf8;
border: 1px solid rgba(76, 107, 87, 0.16);
border-radius: 14px;
font-family: system-ui, sans-serif;
color: #33302b;
transition: transform 0.3s ease, box-shadow 0.3s ease;
}
:host(:hover) {
transform: translateY(-4px);
box-shadow: 0 16px 36px rgba(80, 72, 55, 0.1);
}
h3 {
margin: 0 0 6px;
font-family: Georgia, serif;
font-size: 19px;
letter-spacing: 1px;
}
time {
display: block;
font-size: 11px;
letter-spacing: 2px;
color: #948d81;
margin-bottom: 14px;
}
p { margin: 0; font-size: 14px; line-height: 1.9; color: #4a463f; }
</style>
<article>
<h3><slot name="title">无标题</slot></h3>
<time><slot name="date"></slot></time>
<p><slot>暂无内容</slot></p>
</article>
`;
}
// 3. 属性映射到内容
attributeChangedCallback(name, oldValue, newValue) {
if (oldValue === newValue) return;
if (name === 'title') {
this.shadowRoot.querySelector('slot[name="title"]').textContent = newValue;
}
if (name === 'date') {
this.shadowRoot.querySelector('slot[name="date"]').textContent = newValue;
}
}
// 4. 生命周期:插入页面 / 移除页面
connectedCallback() {
this.setAttribute('role', 'article');
}
disconnectedCallback() {
// 清理定时器、事件监听等资源
}
}
// 5. 注册标签:必须包含连字符
customElements.define('note-card', NoteCard);
在页面中使用
<note-card title="山中笔记" date="2026-03-18">
雾还没散,石阶湿滑。慢一点走,山不会跑。
</note-card>
<script type="module" src="note-card.js"></script>
Shadow DOM 的价值:组件内部的 h3、p 样式不会影响外部,外部样式也不会意外污染组件。配合 CSS 自定义属性,还能让外部「主题化」组件。
06IntersectionObserver 与 ResizeObserver
传统做法监听 scroll 事件计算位置,开销大且容易卡顿。Observer API 由浏览器在合适的时机通知你,性能好得多。
// 1. 元素进入视口时淡入(可用于懒加载、曝光统计)
const io = new IntersectionObserver((entries, observer) => {
entries.forEach(entry => {
if (!entry.isIntersecting) return;
entry.target.classList.add('visible');
observer.unobserve(entry.target); // 只触发一次
});
}, {
root: null, // 以视口为参照
rootMargin: '0px 0px -60px 0px',
threshold: 0.15 // 露出 15% 时触发
});
document.querySelectorAll('.reveal').forEach(el => io.observe(el));
// 2. 图片懒加载
const imgObserver = new IntersectionObserver(entries => {
entries.forEach(entry => {
if (!entry.isIntersecting) return;
const img = entry.target;
img.src = img.dataset.src;
imgObserver.unobserve(img);
});
}, { rootMargin: '200px' });
document.querySelectorAll('img[data-src]').forEach(img => imgObserver.observe(img));
// 3. 监听元素尺寸变化(替代 window.resize)
const ro = new ResizeObserver(entries => {
entries.forEach(entry => {
const { width, height } = entry.contentRect;
console.log('容器尺寸:', width, height);
});
});
ro.observe(document.querySelector('.chart'));
// 4. 监听 DOM 结构变化
const mo = new MutationObserver(mutations => {
mutations.forEach(m => console.log('节点变化:', m.type));
});
mo.observe(document.body, { childList: true, subtree: true });
// 5. 无限滚动
const sentinel = document.querySelector('#sentinel');
const loadMore = new IntersectionObserver(entries => {
if (entries[0].isIntersecting) fetchNextPage();
});
loadMore.observe(sentinel);
07Web Animations API
当动画需要暂停、拖动进度、动态修改关键帧时,CSS 动画就不够用了。Web Animations API 提供了可编程的动画控制。
const orb = document.querySelector('#waapiOrb');
const animation = orb.animate([
{ transform: 'translateX(-70px) scale(1)', offset: 0 },
{ transform: 'translateX(0) translateY(-20px) scale(1.1)', offset: 0.5 },
{ transform: 'translateX(70px) scale(1)', offset: 1 }
], {
duration: 2600,
iterations: Infinity,
direction: 'alternate',
easing: 'cubic-bezier(0.22, 0.61, 0.36, 1)'
});
// 基本控制
animation.pause();
animation.play();
animation.cancel();
animation.reverse();
// 调速与跳转
animation.playbackRate = 0.5; // 半速
animation.currentTime = 800; // 跳到 0.8 秒
// 监听结束事件
animation.onfinish = () => console.log('动画结束');
// 与 CSS 变量配合
document.documentElement.style.setProperty('--motion', '1');
// 优先遵循用户的减少动效偏好
const reduce = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
if (reduce) animation.cancel();
08Web Worker:把重活搬离主线程
JavaScript 单线程意味着密集计算会冻结页面。Web Worker 在独立线程中运行代码,通过消息与主线程通信,主线程只负责更新界面。
// Worker 线程内:接收任务并返回结果
self.onmessage = function (event) {
const { type, payload } = event.data;
if (type === 'sum') {
// 模拟耗时计算:求 1 到 n 的和(或更复杂的加解密、图像处理)
let total = 0;
for (let i = 0; i < payload; i++) {
total += i;
}
self.postMessage({ type: 'sum-done', payload: total });
}
if (type === 'heavy') {
// 也可以把大数组分块处理,避免一次占用过多内存
const result = payload.map(n => n * 2);
self.postMessage({ type: 'heavy-done', payload: result });
}
};
const worker = new Worker('worker.js');
// 发送任务
worker.postMessage({ type: 'sum', payload: 10_000_000 });
// 接收结果
worker.onmessage = function (event) {
console.log('计算结果:', event.data.payload);
};
worker.onerror = function (err) {
console.error('Worker 出错:', err.message);
};
// 结束线程
// worker.terminate();
| 限制 | 说明 |
|---|---|
| 不能访问 DOM | Worker 中无法直接操作页面元素 |
| 独立作用域 | 不能直接共享主线程变量,只能通过消息传递 |
| 部分 API 不可用 | 如 window、document、alert |
| 同源限制 | Worker 脚本需与页面同源 |
| 通信开销 | 传递大对象会结构化克隆,可用 Transferable 转移所有权 |
09Service Worker 与 PWA
Service Worker 是运行在浏览器后台的脚本,可以拦截网络请求、管理缓存,让网站具备离线能力。配合 Web App Manifest,就能把网站「安装」到桌面。
注册与生命周期
// 必须在 HTTPS 或 localhost 下运行
if ('serviceWorker' in navigator) {
window.addEventListener('load', async () => {
try {
const registration = await navigator.serviceWorker.register('/sw.js', {
scope: '/'
});
console.log('Service Worker 已注册:', registration.scope);
} catch (err) {
console.error('注册失败:', err);
}
});
}
缓存策略:Cache First + 网络更新
const CACHE_NAME = 'shiguang-v1';
const PRECACHE = [
'/',
'/index.html',
'/css.html',
'/assets/css/style.css',
'/assets/js/main.js'
];
// 1. 安装:预缓存核心资源
self.addEventListener('install', event => {
event.waitUntil(
caches.open(CACHE_NAME).then(cache => cache.addAll(PRECACHE))
);
self.skipWaiting(); // 立即激活新版本
});
// 2. 激活:清理旧版本缓存
self.addEventListener('activate', event => {
event.waitUntil(
caches.keys().then(keys =>
Promise.all(
keys.filter(key => key !== CACHE_NAME)
.map(key => caches.delete(key))
)
).then(() => self.clients.claim())
);
});
// 3. 请求拦截:缓存优先,网络兜底
self.addEventListener('fetch', event => {
// 只处理 GET 请求
if (event.request.method !== 'GET') return;
event.respondWith(
caches.match(event.request).then(cached => {
if (cached) return cached;
return fetch(event.request).then(response => {
// 只缓存成功的同源响应
if (!response || response.status !== 200) return response;
const copy = response.clone();
caches.open(CACHE_NAME).then(cache => {
cache.put(event.request, copy);
});
return response;
}).catch(() => {
// 离线且未缓存时,返回离线页
return caches.match('/offline.html');
});
})
);
});
// 4. 后台同步 / 推送通知也可在此扩展
self.addEventListener('push', event => {
const data = event.data ? event.data.json() : {};
event.waitUntil(
self.registration.showNotification(data.title || '新消息', {
body: data.body || ''
})
);
});
Web App Manifest
{
"name": "拾光前端 · 学习手记",
"short_name": "拾光前端",
"start_url": "/",
"display": "standalone",
"background_color": "#faf7f0",
"theme_color": "#4c6b57",
"lang": "zh-CN",
"icons": [
{ "src": "/icons/192.png", "sizes": "192x192", "type": "image/png" },
{ "src": "/icons/512.png", "sizes": "512x512", "type": "image/png" },
{ "src": "/icons/maskable.png", "sizes": "512x512", "type": "image/png", "purpose": "maskable" }
]
}
缓存策略没有银弹:HTML 适合 Network First(保证更新及时),静态资源适合 Cache First(加载快),接口数据适合 Stale While Revalidate(先给旧数据再更新)。上线前务必考虑缓存版本的清理逻辑。
10性能优化与 Core Web Vitals
性能不是最后再做的「优化阶段」,而是从写第一行 HTML 就应注意的习惯。先测量,再优化,避免凭感觉下药。
三个核心指标
| 指标 | 含义 | 良好阈值 |
|---|---|---|
| LCP 最大内容绘制 | 主要内容出现在屏幕上的时间 | ≤ 2.5s |
| INP 交互到下一次绘制 | 用户操作后页面的响应速度 | ≤ 200ms |
| CLS 累积布局偏移 | 页面元素意外移动的程度 | ≤ 0.1 |
可落地的优化清单
- 图片:使用 WebP / AVIF,写明宽高,首屏外
loading="lazy",首屏图可加fetchpriority="high"。 - 字体:
font-display: swap,只加载需要的字重,中文字体建议子集化。 - 脚本:能
defer就defer,非关键脚本动态import()。 - CSS:首屏关键样式内联,其余异步加载;避免过深的选择器与大量不必要的动画。
- 渲染:动画用
transform/opacity;避免频繁读取布局属性造成强制同步布局。 - 资源:开启 HTTP 缓存与压缩,静态资源加 hash 文件名,长缓存。
- 第三方:统计、客服等脚本尽量延迟,或放到 Web Worker 中。
// 1. 测量 LCP
new PerformanceObserver(list => {
const entries = list.getEntries();
const last = entries[entries.length - 1];
console.log('LCP:', last.startTime.toFixed(0) + 'ms', last.element);
}).observe({ type: 'largest-contentful-paint', buffered: true });
// 2. 测量布局偏移
new PerformanceObserver(list => {
list.getEntries().forEach(entry => {
if (!entry.hadRecentInput) {
console.log('CLS 贡献:', entry.value);
}
});
}).observe({ type: 'layout-shift', buffered: true });
// 3. 测量长任务(超过 50ms 会阻塞交互)
new PerformanceObserver(list => {
list.getEntries().forEach(entry => {
console.warn('长任务:', entry.duration.toFixed(0) + 'ms');
});
}).observe({ type: 'longtask', buffered: true });
// 4. 手动打点
performance.mark('render-start');
renderList();
performance.mark('render-end');
performance.measure('渲染耗时', 'render-start', 'render-end');
// 5. 空闲时做低优先级工作
requestIdleCallback(deadline => {
while (deadline.timeRemaining() > 0 && tasks.length) {
tasks.shift()();
}
});
// 6. 批量读写 DOM,避免布局抖动
// 错误:每次循环都读一次 offsetHeight
// 正确:先读后写,或使用 requestAnimationFrame 统一处理
测量工具:Chrome DevTools 的 Lighthouse、Performance 面板、Coverage 面板;线上可用 web-vitals 库上报真实用户数据(RUM)。
11前端安全基础
前端不是「只负责好看」。很多安全问题就发生在浏览器端,了解原理才能在写代码时避开。
| 风险 | 原理 | 防御 |
|---|---|---|
| XSS 跨站脚本 | 恶意脚本被注入页面并执行 | textContent、转义、CSP、HttpOnly Cookie |
| CSRF 跨站请求伪造 | 借用户已登录状态发起请求 | CSRF Token、SameSite Cookie、校验 Origin |
| 点击劫持 | 用透明 iframe 诱导点击 | X-Frame-Options、CSP frame-ancestors |
| 开放重定向 | 跳转参数被篡改为恶意站点 | 白名单校验跳转地址 |
| 供应链风险 | 第三方脚本 / 依赖被篡改 | 锁定版本、SRI 完整性校验 |
// ❌ 危险:用户输入直接拼进 HTML
container.innerHTML = `<p>${userInput}</p>`;
// ✅ 安全:使用 textContent
const p = document.createElement('p');
p.textContent = userInput;
container.append(p);
// 如果必须渲染 HTML,先转义
function escapeHTML(str) {
return str.replace(/[&<>"']/g, ch => ({
'&': '&', '<': '<', '>': '>',
'"': '"', "'": '''
}[ch]));
}
// 外链加上 noopener,防止新页面通过 window.opener 操控原页面
// <a target="_blank" rel="noopener noreferrer">
// CSP:在 HTTP 头或 meta 中限制资源来源
// Content-Security-Policy:
// default-src 'self';
// img-src 'self' https: data:;
// script-src 'self' https://trusted.cdn.com;
// frame-ancestors 'none';
// SRI:校验第三方脚本完整性
// <script src="https://cdn.example.com/lib.js"
// integrity="sha384-xxxx"
// crossorigin="anonymous"></script>
永远不要相信用户输入:不仅是表单,还包括 URL 参数、localStorage、第三方接口返回的数据。前端校验是为了体验,后端校验才是安全底线。
12综合练习:给本站加一点「高级感」
把本章能力组合起来,给自己的页面加三个小功能。每一个都不复杂,但都能明显提升体验。
- 滚动进度条:监听滚动,把
scrollY / (scrollHeight - innerHeight)映射为顶部进度条宽度。本站已经默认实现。 - 图片懒加载:用
IntersectionObserver替换loading="lazy",并加上淡入动画。 - 自定义组件:把「读书卡片」改造成
<book-card>,用 Shadow DOM 隔离样式,属性传入书名与作者。
const bar = document.querySelector('.read-progress');
function updateProgress() {
const doc = document.documentElement;
const max = doc.scrollHeight - window.innerHeight;
const ratio = max > 0 ? window.scrollY / max : 0;
bar.style.width = Math.min(ratio * 100, 100) + '%';
}
// passive: true 告诉浏览器不会阻止滚动,提升滚动性能
window.addEventListener('scroll', updateProgress, { passive: true });
window.addEventListener('resize', updateProgress);
updateProgress();
const images = document.querySelectorAll('img[data-src]');
const observer = new IntersectionObserver((entries, obs) => {
entries.forEach(entry => {
if (!entry.isIntersecting) return;
const img = entry.target;
img.src = img.dataset.src;
img.removeAttribute('data-src');
img.addEventListener('load', () => {
img.classList.add('is-loaded');
}, { once: true });
obs.unobserve(img);
});
}, { rootMargin: '160px 0px' });
images.forEach(img => observer.observe(img));
最后一句:高级 API 不难,难的是判断「是否需要它」。能用 HTML + CSS 解决的,就不要引入 JavaScript;能用原生能力解决的,就不要引入重量级依赖。克制,是前端工程师最珍贵的能力。
接下来去 实战项目,把所学真正拼成作品。