PWA(渐进式Web应用)
PWA(渐进式Web应用)实现策略
离线缓存(Service Worker)
Service Worker是PWA的核心技术,通过缓存资源实现离线访问。注册Service Worker并定义缓存策略:
// 注册Service Worker
if ('serviceWorker' in navigator) {navigator.serviceWorker.register('/sw.js').then(registration => {console.log('SW registered');});
}// sw.js缓存策略(Cache First)
const CACHE_NAME = 'v1';
self.addEventListener('install', event => {event.waitUntil(caches.open(CACHE_NAME).then(cache => {return cache.addAll(['/','/index.html','/styles.css','/script.js']);}));
});self.addEventListener('fetch', event => {event.respondWith(caches.match(event.request).then(response => {return response || fetch(event.request);}));
});
推送通知
通过Push API和Notification API实现:
// 请求通知权限
Notification.requestPermission().then(permission => {if (permission === 'granted') {navigator.serviceWorker.ready.then(registration => {registration.showNotification('Title', {body: 'Message content',icon: '/icon.png'});});}
});// 后台Push事件处理(sw.js)
self.addEventListener('push', event => {const data = event.data.json();const options = {body: data.body,icon: 'img/icon.png'};event.waitUntil(self.registration.showNotification(data.title, options));
});
性能优化
- 预加载关键资源:使用
<link rel="preload">
加载关键CSS/JS - 代码分割:动态导入模块
import('./module.js').then(module => {module.run();
});
- Web Workers:将计算密集型任务移至后台线程
WebAssembly应用场景
高性能计算(矩阵运算)
C++编写计算逻辑,通过Emscripten编译为WASM:
// matrix.cpp
extern "C" {void multiplyMatrices(float* a, float* b, float* c, int size) {for (int i = 0; i < size; i++) {for (int j = 0; j < size; j++) {c[i*size+j] = 0;for (int k = 0; k < size; k++) {c[i*size+j] += a[i*size+k] * b[k*size+j];}}}}
}
编译命令:
emcc matrix.cpp -o matrix.js -s EXPORTED_FUNCTIONS="['_multiplyMatrices']" -s MODULARIZE=1
JavaScript调用:
const Module = await import('./matrix.js');
const result = new Float32Array(size * size);
Module._multiplyMatrices(aPtr, bPtr, resultPtr, size);
游戏开发(渲染优化)
Unity导出WebAssembly案例:
// 加载Unity WebGL构建
const gameInstance = UnityLoader.instantiate("gameContainer","Build/WebGL.json",{ onProgress: UnityProgress }
);// 与JavaScript通信
gameInstance.SendMessage('GameObject', 'MethodName', 'message');
WASM与JS交互
共享内存实现高效数据交换:
// JavaScript侧
const memory = new WebAssembly.Memory({ initial: 1 });
const importObject = { env: { memory } };// WebAssembly侧 (WAT格式)
(module(import "env" "memory" (memory 1))(func $update (param $offset i32) (param $value i32)(i32.store (local.get $offset) (local.get $value)))(export "update" (func $update))
)
性能关键点:
- 使用
WebAssembly.instantiateStreaming
加速加载 - 避免频繁WASM/JS边界调用
- 利用SIMD指令(Android Chrome 91+支持)
所有代码示例均需配合构建工具(如Webpack)配置wasm-loader和适当的MIME类型支持。