HTML Subresource Integrity and Content Security Policy
Pin the expected resource bytes
Subresource Integrity (SRI) verifies fetched script or stylesheet bytes against a cryptographic digest. The integrity attribute contains an algorithm and base64 digest; changing a pinned file requires updating the digest. For cross-origin SRI, the response must also satisfy CORS. The following fixed CSS file is represented by an inline data URL solely for this demonstration; the digest is computed from exactly the CSS bytes.
<link rel="stylesheet" href="data:text/css,p%7Bcolor%3A%20green%3B%7D" integrity="sha384-5/7ZGtZGuayqyKA8r0eRBBZJU7Zm6kZdJbh5o5Fy0Ui/Y3ZL5/clHAOFCSlbri7b"><p>Integrity metadata example</p>The link contains a digest; this check verifies metadata, not network SRI enforcement.
Restrict script execution with CSP
Content Security Policy (CSP) restricts what the browser may load or execute. This isolated full document places script-src 'none' before a harmless inline script; if enforced, the paragraph remains unchanged. Prefer HTTP response headers in deployed applications; a meta policy only affects subsequent content.
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="Content-Security-Policy" content="script-src 'none'"> <title>CSP demo</title> </head> <body> <p id="status">Unchanged</p> <script>document.querySelector("#status").textContent = "Changed";</script> </body></html>The harmless inline script is blocked.
Know the limits of meta policies
A meta CSP cannot deliver report-only mode, frame-ancestors or the sandbox directive. Configure those through HTTP response headers when applicable. This static example restricts object embedding and base URLs; it is not a complete production policy. A production policy should match actual dependencies, use safe script handling and be tested before enforcement.
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="Content-Security-Policy" content="object-src 'none'; base-uri 'none'"> <title>Policy example</title> </head> <body> <p>Read the policy.</p> </body></html>The document declares two restrictions.
Common mistakes and practice
SRI does not prove a library is safe; it pins bytes. CSP does not fix unsafe DOM insertion. Review dependencies, use HTTPS, prefer response-header policies, and test with controlled fixtures. Never weaken a policy just to silence an error.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
HTML Subresource Integrity and Content Security Policy — Knowledge Check
Apply the security, privacy and performance concepts taught in this lesson.
What does SRI check?
What happens when pinned content changes?
What does script-src none prohibit?
Which cannot be delivered via meta CSP?
Does SRI guarantee that pinned code is benign?