integrity 与 crossorigin 必须成对出现且值合法,否则 SRI 校验静默失效;仅支持 script 和 link[rel=stylesheet];哈希须基于线上实际响应体生成,多哈希需严格格式,校验失败仅警告不报错。

integrity + crossorigin 必须成对出现,否则校验静默失效
浏览器只在校验跨域资源时才读取 integrity 值,而是否走跨域流程,完全由 crossorigin 属性决定。漏写、拼错(如 crossorigin="anonymouse")、或值不合法(如 use-credentials 但服务端没返回 Access-Control-Allow-Credentials: true),都会导致整个校验被跳过——控制台不会报错,只会显示 Failed to find a valid digest in the 'integrity' attribute 或直接白屏/样式丢失。
常见错误写法:
-
<link rel="stylesheet" href="https://cdn.example.com/style.css" integrity="sha384-xxx">→ 缺crossorigin,无效 -
<link rel="stylesheet" href="https://cdn.example.com/style.css" integrity="sha384-xxx" crossorigin="">→ Firefox 可能忽略空字符串,建议明确写anonymous -
<link rel="stylesheet" href="/style.css" integrity="sha384-xxx" crossorigin="anonymous">→ 同源资源加crossorigin="anonymous"是允许的,且必须加,否则仍不校验
哈希值必须基于线上实际响应体生成,不是本地文件
本地开发时用 npm install 下载的 bootstrap.min.css,和你最终部署到 CDN 上的文件,哪怕只差一个空格、BOM、gzip 压缩层、或重定向跳转,哈希就完全不同。浏览器校验的是它真正从网络拿到的字节流,不是你本地磁盘上的副本。
可靠生成方式(命令行):
立即学习“前端免费学习笔记(深入)”;
- 用
curl -sL https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css | openssl dgst -sha384 -binary | openssl base64 -A——-sL确保静默并跟随重定向,-binary和-A保证输出格式与浏览器内部比对逻辑一致 - 别用
cat bootstrap.min.css | openssl...:本地文件可能含 CRLF/LF 差异、BOM、未压缩、或未经 CDN 的 minify 流程 - 别依赖在线生成器粘贴代码:它们无法模拟 CDN 的重定向、Vary 头、编码协商(如
Accept-Encoding: br)
只支持 <link rel="stylesheet">,其他 link 类型加了也白费
integrity 属性仅对 <script> 和 <link rel="stylesheet"> 生效。以下写法全部无效,浏览器既不校验也不警告:
<link rel="icon" href="/favicon.ico" integrity="sha384-xxx"><link rel="preload" as="font" href="/font.woff2" integrity="sha384-xxx"><link rel="manifest" href="/manifest.json" integrity="sha384-xxx">
如果你需要校验非 CSS 的资源(比如字体、JSON),得靠服务端签名 + JS 主动 fetch + 手动比对哈希,integrity 原生不支持。
多个哈希值空格分隔,但顺序和格式必须严格
你可以提供多套哈希应对兼容性,例如同时支持 sha384 和 sha256:
<link rel="stylesheet" href="style.css" integrity="sha384-abc sha256-def" crossorigin="anonymous">
浏览器会从左到右依次尝试,一旦某个匹配即通过。但要注意:
- 第一个哈希如果格式错误(比如少写了
sha384-前缀),整个integrity属性会被当作无效,后续哈希也不再检查 - 不同算法的哈希值不能混用同一份内容——
sha384和sha256必须分别对同一份原始字节流重新计算,不能把sha256值手动改成sha384-前缀 - 推荐统一用
sha384:它在 Safari iOS 13.3+、Chrome、Firefox、Edge 全系支持,抗碰撞更强,且是 W3C 推荐的 SRI 最低安全标准
integrity 值,确认资源确实能加载;再填回去,观察是否真的被拦截——这是验证整条链路是否跑通的唯一可靠方式。



















