Can the integrity attribute be used with both script and link tags in HTML?

Hello,
I’ve been researching the integrity attribute and noticed that most examples only show it being used with <script> tags. For example:

<script src="script.js" integrity="sha256-0USrj4sQQTNqgzXcG6YOZrppFBSGKt3XS8KRgRzfIEk=" crossorigin="anonymous"></script>

This made me wonder if the integrity attribute can also be applied to <link> tags for CSS files. Is it possible to use integrity with CSS in the same way it’s used with scripts?

<link rel="stylesheet" href="main.css" integrity? >

You might wonder why I didn’t just try it myself. Well, I did, and the CSS still loads fine. However, I’m not sure if adding the integrity attribute actually has any effect on CSS files. I would appreciate any feedback on this.

Here’s what MDN has to say: https://developer.mozilla.org/en-US/docs/Web/API/HTMLLinkElement/integrity

1 Like

Yep, you can totally use the integrity attribute with both <script> and <link> tags. It’s part of Subresource Integrity (SRI), which basically makes sure the file you’re loading (whether it’s a JS file or a CSS file) hasn’t been messed with.

So, for your CSS:

<link rel="stylesheet" href="main.css" integrity="sha256-abcdefg1234567hijklmnopqrstuvwxyz=" crossorigin="anonymous">

It works just like it does with <script> tags. The browser checks the file’s hash against what you’ve got in the integrity attribute. If they don’t match, the file doesn’t load.

Most examples you see might show it with scripts, but it’s totally valid and useful for CSS too. If your CSS loaded fine with the integrity attribute, then it’s probably doing its job. Just make sure the hash is correct for the specific file, and you’re good to go.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.