diff --git a/src/utils/image/imageCacheManager.js b/src/utils/image/imageCacheManager.js index 3f839b5..9bf6569 100644 --- a/src/utils/image/imageCacheManager.js +++ b/src/utils/image/imageCacheManager.js @@ -1,5 +1,6 @@ // src/utils/imageCacheManager.js import { IMAGE_CACHE_VERSION } from '@/config/imageCacheVersion' +import { useDebounce } from '@/utils/useDebounce' class ImageCacheManager { constructor() { @@ -20,6 +21,9 @@ class ImageCacheManager { this.pendingRequests = new Map() // 底层请求管理:包含重试次数 { url: { promise, retries } } this.maxRetries = 3 // 最大重试次数 + // ✅ 新增:防抖版本的缓存限制检查(1 秒防抖,合并多次调用) + this.enforceCacheLimitsDebounced = useDebounce(this.enforceCacheLimits.bind(this), 1000, false) + this.init() } @@ -170,8 +174,11 @@ class ImageCacheManager { try { const response = await cache.match(key) if (response) { - const blob = await response.blob() - cacheEntries.push({ key, size: blob.size, response }) + // ✅ 优化:优先使用 Content-Length 头,避免 blob() 开销 + const contentLength = response.headers.get('content-length') + // 使用与添加时相同的兜底逻辑 + const size = contentLength ? parseInt(contentLength, 10) : (await response.blob()).size // 兜底方案 + cacheEntries.push({ key, size, response }) } } catch (e) { console.warn('无法获取缓存项大小:', key.url) @@ -207,7 +214,8 @@ class ImageCacheManager { if (response) { const contentLength = response.headers.get('content-length') if (contentLength) { - const size = parseInt(contentLength, 10) + // 使用与添加时相同的逻辑 + const size = contentLength ? parseInt(contentLength, 10) : (await response.blob()).size // 兜底 this._updateCacheSize(cacheName, -size) // 减少缓存大小 } } @@ -231,6 +239,7 @@ class ImageCacheManager { console.log('正在清除旧的OSS图片缓存:', oldImageCaches) await Promise.all(oldImageCaches.map((name) => caches.delete(name))) + this.currentImageCacheSize = 0 // 重置计数器 } catch (error) { console.warn('清理旧的OSS图片缓存失败:', error) } @@ -249,6 +258,7 @@ class ImageCacheManager { console.log('正在清除旧的本地assets缓存:', oldAssetCaches) await Promise.all(oldAssetCaches.map((name) => caches.delete(name))) + this.currentAssetCacheSize = 0 // 重置计数器 } catch (error) { console.warn('清理旧的本地assets缓存失败:', error) } @@ -266,6 +276,9 @@ class ImageCacheManager { console.log('正在清除所有图片缓存:', allCaches) await Promise.all(allCaches.map((name) => caches.delete(name))) + // 重置计数器 + this.currentImageCacheSize = 0 + this.currentAssetCacheSize = 0 } catch (error) { console.warn('清理所有图片缓存失败:', error) } @@ -451,7 +464,8 @@ class ImageCacheManager { } // 异步检查缓存限制 - this.enforceCacheLimits(cache, cacheName).catch((error) => { + // ✅ 修复:包装为 Promise 确保错误捕获 + Promise.resolve(this.enforceCacheLimitsDebounced(cache, cacheName)).catch((error) => { console.warn('检查缓存限制时出错:', error) }) }