What Is Subresource Integrity (SRI)

Learn what Subresource Integrity (SRI) is, how it protects your website from tampered third-party scripts, and why every production site should use integrity attributes.

SRI Basics

Detailed Explanation

Understanding Subresource Integrity

Subresource Integrity (SRI) is a W3C security specification that allows browsers to verify that files fetched from external servers — such as CDNs — have not been tampered with. When you add an integrity attribute to a <script> or <link> tag, the browser computes a cryptographic hash of the downloaded file and compares it against the hash you provided. If the hashes do not match, the browser refuses to execute the script or apply the stylesheet.

How SRI Works

The integrity attribute contains a hash algorithm prefix followed by a Base64-encoded digest:

<script
  src="https://cdn.example.com/lib.js"
  integrity="sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/ux..."
  crossorigin="anonymous"
></script>

When the browser downloads lib.js, it:

  1. Downloads the resource from the CDN
  2. Computes the SHA-384 hash of the downloaded content
  3. Compares the computed hash with the value in the integrity attribute
  4. Blocks execution if the hashes differ, logging an error to the console

Why SRI Matters

Without SRI, a compromised CDN or a man-in-the-middle attacker could inject malicious code into a popular library. Because thousands of websites load the same CDN-hosted files, a single compromised file could affect millions of users — a supply-chain attack. SRI ensures that even if the CDN is breached, the altered file will be rejected by every browser that checks its integrity hash.

Supported Resources

SRI currently works with two HTML elements:

  • <script> — JavaScript files loaded via src
  • <link rel="stylesheet"> — CSS files loaded via href

Fetch API also supports SRI via the integrity option, allowing programmatic integrity verification for any fetched resource.

Browser Behavior on Failure

When an SRI check fails, the browser fires an error event on the element and does not execute or apply the resource. The page continues to load, but the blocked resource is treated as if it returned a network error. This fail-safe behavior is critical: it is better to have a broken page than to run tampered code.

Use Case

Every production website that loads JavaScript or CSS from a CDN should implement SRI. It is especially important for e-commerce sites handling payment data, banking portals, healthcare applications, and any site processing sensitive user information. SRI is a zero-cost defense layer that prevents supply-chain attacks with just two HTML attributes.

Try It — SRI Hash Generator

Open full tool