| 1 | // 性能优化模块 |
| 2 | class PerformanceOptimizer { |
| 3 | constructor() { |
| 4 | this.isOnline = navigator.onLine; |
| 5 | this.observers = new Map(); // Track observers for cleanup |
| 6 | this._webpSupported = null; // 缓存 WebP 检测结果 |
| 7 | this._parallaxElements = null; // 缓存视差元素查询 |
| 8 | this.init(); |
| 9 | } |
| 10 | |
| 11 | init() { |
| 12 | this.setupNetworkListeners(); |
| 13 | this.optimizeImages(); |
| 14 | this.setupScrollOptimization(); |
| 15 | this.setupIntersectionObserver(); |
| 16 | this.setupTouchOptimization(); |
| 17 | this.setupVisibilityHandler(); |
| 18 | } |
| 19 | |
| 20 | // Cleanup method to prevent memory leaks |
| 21 | destroy() { |
| 22 | // Clean up all observers |
| 23 | this.observers.forEach((observer, key) => { |
| 24 | observer.disconnect(); |
| 25 | }); |
| 26 | this.observers.clear(); |
| 27 | } |
| 28 | |
| 29 | // (Service Worker 已停用) |
| 30 | |
| 31 | // 设置网络监听器 |
| 32 | setupNetworkListeners() { |
| 33 | window.addEventListener('online', () => { |
| 34 | this.isOnline = true; |
| 35 | this.showNetworkStatus('网络已连接', 'success'); |
| 36 | }); |
| 37 | |
| 38 | window.addEventListener('offline', () => { |
| 39 | this.isOnline = false; |
| 40 | this.showNetworkStatus('网络已断开,使用离线模式', 'warning'); |
| 41 | }); |
| 42 | } |
| 43 | |
| 44 | // 显示网络状态 |
| 45 | showNetworkStatus(message, type) { |
| 46 | const toast = document.createElement('div'); |
| 47 | toast.className = `network-status ${type} fade-in`; |
| 48 | toast.textContent = message; |
| 49 | |
| 50 | document.body.appendChild(toast); |
| 51 | |
| 52 | setTimeout(() => { |
| 53 | toast.classList.add('fade-out'); |
| 54 | setTimeout(() => toast.remove(), 300); |
| 55 | }, 3000); |
| 56 | } |
| 57 | |
| 58 | // 图片优化 |
| 59 | optimizeImages() { |
| 60 | const images = document.querySelectorAll('img[data-src]'); |
nothing calls this directly
no outgoing calls
no test coverage detected