@@ -8,41 +8,49 @@ export function asyncDrawImage(options: {
88 timeout ?: number ;
99 mediaCache ?: flruCache < HTMLElement | null > ;
1010 crossOrigin ?: string | null ;
11+ cacheKeyPrefix ?: string ;
1112} ) : Promise < HTMLImageElement > {
1213 const {
1314 src,
1415 fallback,
1516 timeout = 10000 ,
1617 mediaCache,
1718 crossOrigin = 'Anonymous' ,
19+ cacheKeyPrefix,
1820 } = options ;
1921
22+ const cacheKey = cacheKeyPrefix ? `${ cacheKeyPrefix } :${ src } ` : src ;
23+
2024 return new Promise ( ( resolve , reject ) => {
21- if ( mediaCache ?. has ( src ) ) {
22- const cacheImg = mediaCache . get ( src ) ;
25+ if ( mediaCache ?. has ( cacheKey ) ) {
26+ const cacheImg = mediaCache . get ( cacheKey ) ;
2327
24- if ( cacheImg ) {
25- resolve ( mediaCache . get ( src ) as HTMLImageElement ) ;
26- } else {
27- reject ( loadError ) ;
28+ if ( cacheImg instanceof HTMLImageElement ) {
29+ resolve ( cacheImg ) ;
30+
31+ return ;
2832 }
2933
30- return ;
34+ if ( cacheImg === null ) {
35+ reject ( loadError ) ;
36+
37+ return ;
38+ }
3139 }
3240
3341 const cacheResolve = ( img : HTMLImageElement ) => {
34- mediaCache ?. set ( src , img ) ;
42+ mediaCache ?. set ( cacheKey , img ) ;
3543 resolve ( img ) ;
3644 } ;
3745
3846 const cacheReject = ( error : Error ) => {
39- mediaCache ?. set ( src , null ) ;
47+ mediaCache ?. set ( cacheKey , null ) ;
4048 reject ( error ) ;
4149 } ;
4250
4351 const processFallback = ( ) => {
4452 if ( fallback ) {
45- // 如果仍然加载失败,尝试 fallback
53+ // fallback 图片使用原始URL作为缓存key(不带前缀),避免污染主缓存
4654 asyncDrawImage ( {
4755 src : fallback ,
4856 timeout,
@@ -63,6 +71,7 @@ export function asyncDrawImage(options: {
6371 timeout,
6472 mediaCache,
6573 crossOrigin : null ,
74+ cacheKeyPrefix,
6675 } )
6776 . then ( cacheResolve )
6877 . catch ( processFallback ) ;
0 commit comments