SRI hash

Per W3C SRI

Subresource Integrity hash (sha256/384/512) for externally embedded scripts.

What is this, and when do I need it?

What is this?

SRI (Subresource Integrity) is a hash you add to every externally embedded script or stylesheet tag (<script src="...">, <link rel="stylesheet">). The browser fetches the file, computes the hash, and compares: if it differs, the file is not executed.

That protects you against compromised CDN providers and accidental file changes. If an attacker takes over the jQuery CDN and injects malicious code, the browser blocks the modified script on your page.

When do I need it?

As soon as you load scripts or stylesheets from a foreign server - typically CDN paths like cdnjs, jsdelivr, unpkg. For files from your own server path, SRI is not needed.

Caveat: SRI only works for static file versions. With rotating versions (e.g. always "latest"), you must refresh the hash on every update - or pin the version in the URL.

SRI hashes bind a resource to exactly this byte content. If a CDN changes the content or a MITM swaps the script, the browser refuses to execute it. All three algorithms (sha256, sha384, sha512) are accepted per W3C SRI § 3.4.3 and cryptographically sound; the choice is primarily convention - sha384 is the most common recommendation of the Web Application Security Working Group.

Multiple hashes per resource are allowed: integrity="sha384-X sha512-Y" (space-separated). The browser picks the strongest verifiable hash. Useful when migrating between algorithms. Scope: SRI only applies to <script>, <link rel="stylesheet">, <link rel="preload"> and <link rel="modulepreload">. On images or iframes, integrity has no effect.

crossorigin="anonymous" is not mandatory for same-origin resources but avoids cache inconsistencies. crossorigin="use-credentials" only set when the CDN endpoint must send cookies - that breaks shared browser caching.