背景与价值预加载能显著优化首屏,但需要白名单与正确的as/importance设置,避免错用与安全风险。统一规范白名单:仅受控域与版本化路径允许预加载。as设置:与资源类型匹配(script/style/font/image/fetch)。importance:关键资源使用high,其余low。核心实现校验与生成const allowOrigins = new Set(['https://cdn.example.com','https://assets.example.com']) function originAllowed(url: string): boolean { try { const u = new URL(url); return allowOrigins.has(u.origin) } catch { return false } } function validAs(as: string): boolean { return ['script','style','font','image','fetch'].includes(as) } function versioned(path: string): boolean { return /@[0-9]+\.[0-9]+\.[0-9]+\//.test(path) || /\.[a-f0-9]{8,}\./.test(path) } function makePreload(url: string, as: string, importance: 'high'|'low'='high', crossOrigin?: 'anonymous'|'use-credentials'): HTMLLinkElement | null { try { const u = new URL(url) if (!originAllowed(url)) return null if (!versioned(u.pathname)) return null if (!validAs(as)) return null const el = document.createElement('link') el.rel = 'preload' el.href = url el.as = as ;(el as any).importance = importance if (crossOrigin) el.crossOrigin = crossOrigin document.head.appendChild(el) return el } catch { return null } } 落地建议仅对白名单域与版本化资源开启preload;确保as与资源类型一致并设置适当优先级。验证清单是否命中白名单与版本化路径;as与importance是否正确。

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论
立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部
1.914611s