Course contentsShow
← Web Development
Lesson 2937 of 2,98252. Frontend SecurityFree lesson

Adding SRI to Script and Link Tags

Implementing integrity attributes on script and link elements to protect external resources.

Adding SRI to Script and Link Tags

What you'll learn: How to add integrity attributes to <script> and <link> tags to enable Subresource Integrity protection.

Now that you understand how SRI works with cryptographic hashes, it's time to implement it. Adding SRI protection is straightforward: you include an integrity attribute containing the hash, and a crossorigin attribute to enable CORS checks.

Basic Syntax

For a script tag loading from a CDN:

<script 
  src="https://cdn.example.com/library.js"
  integrity="sha384-abc123def456..."
  crossorigin="anonymous">
</script>

For a stylesheet:

<link 
  rel="stylesheet"
  href="https://cdn.example.com/styles.css"
  integrity="sha384-xyz789uvw012..."
  crossorigin="anonymous">

Why crossorigin Matters

The crossorigin attribute is required because SRI needs to read the resource content to verify the hash. Without it, the browser can't perform the integrity check on cross-origin resources. Use "anonymous" if you don't need credentials, or "use-credentials" if the resource requires authentication.

Multiple Hash Algorithms

You can provide multiple hashes for fallback compatibility:

<script 
  src="https://cdn.example.com/app.js"
  integrity="sha256-hash1... sha384-hash2..."
  crossorigin="anonymous">
</script>

The browser will use the strongest algorithm it supports.

Key Takeaway: Add the integrity attribute with your hash and crossorigin="anonymous" to <script> and <link> tags to enable SRI protection—the browser will now refuse to execute resources that don't match the specified hash.