4月22日 web学习笔记
一、Web 组件与自定义元素
Web 组件简介
定义:使用浏览器原生 API 构建可重用的组件。
核心概念:
自定义元素(Custom Elements):定义新的 HTML 元素。
影子 DOM(Shadow DOM):封装组件样式和逻辑。
HTML 模板(HTML Templates):定义组件结构。
自定义元素
示例:
JavaScript
class HelloWorld extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
}
connectedCallback() {
this.shadowRoot.innerHTML = `
<style>
p {
color: blue;
font-size: 1.5em;
}
</style>
<p>Hello, World!</p>
`;
}
}
customElements.define('hello-world', HelloWorld);
使用:
HTML
影子 DOM
示例:
JavaScript
class CustomButton extends HTMLElement {
constructor() {
super();
const shadow = this.attachShadow({ mode: 'open' });
shadow.innerHTML = <style> button { padding: 10px 20px; background: #3498db; color: white; border: none; border-radius: 4px; cursor: pointer; } button:hover { background: #2980b9; } </style> <button>Click Me</button> ;
}
}
customElements.define('custom-button', CustomButton);
使用:
HTML
HTML 模板
示例:
HTML
使用:
HTML
二、渐进式 Web 应用(PWA)
PWA 简介
定义:结合 Web 应用和原生应用优势的技术。
核心特性:
离线支持:使用服务工作线程(Service Workers)缓存资源。
安装体验:用户可将应用添加到主屏幕。
推送通知:支持推送通知。
服务工作线程(Service Workers)
安装和激活:
JavaScript
// sw.js
self.addEventListener('install', (event) => {
console.log('Service Worker 安装中...');
event.waitUntil(
caches.open('v1').then((cache) => {
return cache.addAll([
'/',
'/index.html',
'/styles.css',
'/app.js',
]);
})
);
});
self.addEventListener('activate', (event) => {
console.log('Service Worker 激活中...');
});
self.addEventListener('fetch', (event) => {
event.respondWith(
caches.match(event.request).then((response) => {
return response || fetch(event.request);
})
);
});
注册服务工作线程:
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('/sw.js')
.then((registration) => {
console.log('Service Worker 注册成功:', registration);
})
.catch((error) => {
console.error('Service Worker 注册失败:', error);
});
});
}
推送通知
申请权限:
function requestNotificationPermission() {
if ('Notification' in window) {
Notification.requestPermission().then((permission) => {
console.log('通知权限:', permission);
});
}
}
发送通知:
JavaScript
function showNotification(title, body) {
if ('Notification' in window && Notification.permission === 'granted') {
new Notification(title, { body });
}
}
Web 应用清单(Web App Manifest)
示例:
JSON
{
"name": "我的 PWA 应用",
"short_name": "PWA 应用",
"description": "一个渐进式 Web 应用示例",
"icons": [
{
"src": "icon.png",
"sizes": "192x192",
"type": "image/png"
}
],
"start_url": "/index.html",
"display": "standalone",
"theme_color": "#3498db",
"background_color": "#f4f4f4"
}
引用清单:
HTML
npm install -g lighthouse
lighthouse https://yourwebsite.com --view
性能指标:
FID(First Input Delay):首次输入延迟。
LCP(Largest Contentful Paint):最大内容绘制。
CLS(Cumulative Layout Shift):累计布局偏移。
用户体验优化
骨架屏:显示加载骨架提升感知性能。
渐进式加载:优先加载关键资源。
示例(骨架屏):
jsx
import React, { useState } from 'react';
function App() {
const [isLoading, setIsLoading] = useState(true);
return (
<div>
{isLoading ? (
<div className="skeleton">
<div className="skeleton-header"></div>
<div className="skeleton-content"></div>
</div>
) : (
<div className="content">
{/* 实际内容 */}
</div>
)}
</div>
);
}
// 模拟加载完成
setTimeout(() => {
setIsLoading(false);
}, 1000);
浙公网安备 33010602011771号