HTML integrity Attribute

Beginner
⏱️ 6 min read
📚 Updated: Jun 2026
🎯 3 Examples
Security & CDN

Introduction

The integrity attribute enables Subresource Integrity (SRI)—a security feature that lets the browser verify an external resource (such as a JavaScript file or stylesheet) has not been tampered with. You provide a cryptographic hash of the expected file content; if the downloaded bytes do not match, the browser blocks the resource instead of running or applying it.

What You’ll Learn

01

SRI Basics

Hash verification.

02

script & link

Where it applies.

03

sha256/384/512

Hash algorithms.

04

crossorigin

Required for CDN SRI.

05

Generate Hash

openssl / SRI tools.

06

Update on Change

Keep hashes in sync.

Purpose of integrity Attribute

The primary purpose of the integrity attribute is to verify that external resources fetched by the browser match the content you expect. This protects users if a CDN is compromised, a man-in-the-middle attack alters a file, or a cached copy differs from the version you audited.

Without SRI, the browser blindly trusts whatever file the URL returns. With integrity, a hash mismatch causes the browser to reject the script or stylesheet—preventing injected or modified code from executing on your page.

🔒
Pair with crossorigin

Cross-origin SRI requires CORS-enabled fetching. Add crossorigin="anonymous" on the same <script> or <link> element when loading from a CDN on another domain.

📝 Syntax

Add integrity to a <script> or <link> element that loads an external file:

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

Syntax Rules

  • Value format: algorithm-base64Hash (e.g. sha384-..., sha256-...).
  • Supported on <script src="..."> and <link href="..." rel="stylesheet"> (and some preload links).
  • Multiple hashes can be space-separated; the browser uses the first algorithm it supports.
  • The hash must match the exact bytes of the fetched file—whitespace or version changes break SRI.
  • Use crossorigin="anonymous" for cross-origin resources so the browser can hash the response body.
  • Regenerate and update the hash whenever you change the external file or CDN version.

💎 Values

The integrity attribute accepts a cryptographic hash representing the expected content of the referenced resource:

  • sha256-... — SHA-256 hash, base64-encoded (common choice).
  • sha384-... — SHA-384 hash, base64-encoded (recommended balance of strength and size).
  • sha512-... — SHA-512 hash, base64-encoded (strongest, longer value).
  • Multiple values — integrity="sha384-abc... sha256-def..." provides algorithm fallbacks.

Generate a hash from the file bytes, then prefix with the algorithm name and a hyphen. Example using OpenSSL for a local file:

generate-hash.sh
openssl dgst -sha384 -binary lib.js | openssl base64 -A

Prepend sha384- to the output and use it as the integrity attribute value.

⚡ Quick Reference

Use CaseExampleNotes
CDN scriptintegrity="sha384-..." on <script>Add crossorigin
CDN stylesheetintegrity="sha384-..." on <link>rel="stylesheet"
Hash mismatchBrowser blocks resourceCheck console for SRI error
File updatedRegenerate hashAny byte change breaks SRI
CORS requiredcrossorigin="anonymous"Cross-origin SRI
Same-originSRI still workscrossorigin optional

Applicable Elements

ElementSupported?Notes
<script src="...">YesPrimary use—verify external JavaScript
<link rel="stylesheet" href="...">YesVerify external CSS
<link rel="preload">YesPreloaded scripts/styles with SRI
Inline <script> (no src)NoNothing external to verify
<img>, <div>NoNot valid on general elements

integrity + crossorigin Together

Scenariointegritycrossorigin
Same-origin scriptOptional SRINot required
CDN (cross-origin) scriptRecommendedanonymous required for SRI
CDN stylesheetRecommendedanonymous required for SRI
Hash failsResource blockedConsole shows integrity error

Examples Gallery

Secure external scripts, stylesheets, and setting integrity with JavaScript before fetch.

👀 Live Preview

SRI flow at a glance:

  1. You host a hash of the expected file in integrity.
  2. The browser downloads the external resource.
  3. It computes a hash of the response bytes.
  4. Match → resource runs. Mismatch → blocked.

SRI protects against CDN compromise and unexpected file changes.

Example — External Script with SRI

Let’s look at an example of how to use the integrity attribute with a <script> tag:

integrity-script.html
<script
  src="https://cdn.example.com/example.js"
  integrity="sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8wC"
  crossorigin="anonymous"></script>
Try It Yourself

How It Works

The browser downloads example.js, hashes the bytes with SHA-384, base64-encodes the result, and compares it to the value after sha384- in the attribute. Only a perfect match allows execution.

Example — External Stylesheet with SRI

Apply the same protection to CSS loaded from a CDN:

integrity-link.html
<link
  rel="stylesheet"
  href="https://cdn.example.com/styles.css"
  integrity="sha384-abc123ExampleReplaceWithRealHash"
  crossorigin="anonymous">
Try It Yourself

How It Works

SRI on stylesheets prevents injected CSS from a compromised CDN. Generate the hash from the exact CSS file bytes you intend to ship.

Dynamic Values with JavaScript

You can set the integrity attribute with JavaScript, but it must be applied before the browser fetches the resource for first-load SRI to take effect:

dynamic-integrity.html
<script id="exampleScript" src="example.js" crossorigin="anonymous"></script>

<script>
  const hashValue = generateHash(exampleScriptContent);
  document.getElementById("exampleScript")
    .setAttribute("integrity", "sha256-" + hashValue);
</script>
Try It Yourself

How It Works

The example computes a SHA-256 hash of known content and assigns it to the script element. For static CDN assets, generate hashes at build time and embed them in your HTML template instead of computing in the browser.

♿ Accessibility

  • Blocked scripts can break functionality — If SRI rejects a critical script, interactive features may fail. Monitor the console and provide fallbacks for essential UI.
  • Do not block required styles silently — A failed stylesheet can harm layout and readability. Test after every hash update.
  • Security benefits all users — SRI helps protect everyone, including assistive technology users, from injected malicious content.
  • Document CDN dependencies — Keep a list of external assets with hashes so updates remain accessible to the whole team.

🧠 How integrity Works

1

Author embeds expected hash

integrity + crossorigin on script/link.

Markup
2

Browser fetches resource

CDN or third-party server responds.

Network
3

Browser hashes response

Compares to integrity attribute.

Verify
=

Trusted resource only

Match runs CSS/JS. Mismatch blocks tampered files.

Browser Support

Subresource Integrity is supported in all modern browsers for <script> and <link rel="stylesheet">. Use crossorigin with cross-origin CDN assets for reliable SRI checks.

HTML5 · Fully supported

Modern SRI support

Chrome, Firefox, Safari, and Edge enforce integrity on external scripts and stylesheets.

98% Browser support
Google Chrome Fully supported
Full support
Mozilla Firefox Fully supported
Full support
Apple Safari Fully supported
Full support
Microsoft Edge Fully supported
Full support
Internet Explorer Not supported
No SRI
Opera Fully supported
Full support
integrity attribute (SRI) 98% supported

Bottom line: Use SRI on CDN scripts and stylesheets in all modern browsers; pair with crossorigin for cross-origin files.

💡 Best Practices

✅ Do

  • Add integrity to critical CDN scripts and stylesheets
  • Pair with crossorigin="anonymous" on cross-origin assets
  • Regenerate hashes when you upgrade library versions
  • Automate hash generation in your build pipeline
  • Monitor the console for SRI failures after deployments

❌ Don’t

  • Use placeholder hashes like sha256-abc123 in production
  • Forget to update integrity after editing the external file
  • Skip crossorigin on cross-origin SRI tags
  • Assume SRI replaces other security measures (CSP, HTTPS)
  • Set integrity only after the browser has already fetched the file

Conclusion

The integrity attribute is a valuable tool for enhancing the security of web applications through Subresource Integrity. It lets browsers verify that external scripts and stylesheets have not been altered since you approved them.

By generating accurate hashes, pairing with crossorigin, and updating values whenever files change, you can reduce the risk of CDN compromise and supply-chain attacks while keeping your pages trustworthy for users.

Key Takeaways

Knowledge Unlocked

Five truths every developer should know about integrity

Bookmark these before loading CDN assets.

5
Core concepts
📄 02

script & link

External resources

Scope
🔢 03

sha384-...

Hash format

Values
🌐 04

crossorigin

CDN requirement

CORS
🔄 05

Update hash

On every file change

Maintenance

❓ Frequently Asked Questions

It enables Subresource Integrity (SRI). The browser hashes the downloaded file and compares it to your expected hash. If they differ, the script or stylesheet is blocked.
<script src="..."> and <link rel="stylesheet" href="..."> (plus some preload links). Inline scripts without src do not use integrity.
Cross-origin resources must be fetched in CORS mode for the browser to read the response body and compute a hash. Use crossorigin="anonymous" on CDN tags.
Hash the file bytes with SHA-256, SHA-384, or SHA-512, base64-encode the digest, and prefix with the algorithm name (e.g. sha384-). Use OpenSSL or an SRI hash generator tool.
The browser refuses to execute the script or apply the stylesheet and logs an integrity error in the developer console. Your page may miss functionality or styling until the hash is corrected.
Yes, with setAttribute("integrity", "sha384-..."), but for first-load verification the attribute should be present before the browser requests the file. Build-time embedding is preferred for static assets.

Secure your CDN resources

Practice the integrity attribute with external scripts and stylesheets in the Try It editor.

Try secure script example →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

5 people found this page helpful