Third-Party Script Security: SRI and Sandboxing
On this page
Learning Objective
Assess the performance, privacy and security risk of third-party scripts, load them with the least impact using async loading, facades, consent gating and workers, protect against tampering with Subresource Integrity, self-hosting and CSP, sandbox untrusted embeds in iframes and govern which scripts are allowed.
Concept Explanation
A typical commercial website loads many scripts it did not write: analytics, tag managers, A/B testing tools, chat widgets, advertising and social embeds, session recording, customer support and personalization tools. Each runs with full access to the page, the DOM, cookies that are not HttpOnly, form fields and the user's keystrokes. Each also costs network requests, main thread time and often more scripts loaded in turn. Third parties are therefore both a performance problem and a security and privacy problem, and they are often added by teams outside engineering through a tag manager.
The security risk is the supply chain. If a third-party provider is compromised, or its CDN is, every site that loads the script runs the attacker's code. Magecart attacks have repeatedly injected card-skimming code into third-party scripts and libraries used on checkout pages, stealing payment details from hundreds of thousands of users of major retailers and airlines. The polyfill.io incident from Day 49 showed the same risk with a domain that changed owners. Day 46 covered the npm side of the supply chain; third-party scripts are the run-time side.
Several controls reduce this risk. Subresource Integrity, an integrity attribute with a cryptographic hash on a script or link tag, makes the browser refuse a file whose contents do not match, so a tampered file on a CDN is blocked. SRI works for versioned, static files; scripts that change without notice, such as most analytics tags, cannot use it, which is an argument for self-hosting a pinned version where licenses permit. A strict CSP (Day 92) limits which scripts can run and where they can send data with connect-src. Sensitive pages, such as checkout and account settings, should load as few third parties as possible, and PCI DSS version 4 now requires an inventory and integrity monitoring of scripts on payment pages.
Untrusted content that does not need access to your page belongs in a sandboxed iframe on another origin. The sandbox attribute removes capabilities by default, scripts, forms, popups, top navigation and same-origin access, and lets you grant only what is needed, for example allow-scripts without allow-same-origin. The allow attribute controls powerful features such as camera and geolocation. Communication then happens through postMessage with origin checks, as in Day 91.
For performance, load third parties with async or defer, after the main content, and only when needed. Facades replace heavy embeds such as video players, maps and chat widgets with a lightweight static preview that loads the real widget on click, which often removes hundreds of kilobytes from the initial load. Consent management should gate tracking scripts so they load only after the user agrees, which is required by privacy laws such as the GDPR in many cases. Tools such as Partytown can run some third-party scripts in a web worker (Day 90). Finally, govern: keep an inventory of every third-party script with its owner, purpose, data access and cost, review new ones like dependencies, remove unused tags regularly and give third parties a performance budget (Day 86).
| Risk or need | Control | Note |
|---|---|---|
| Tampered static file | Subresource Integrity | Versioned files only |
| Provider or domain compromise | Self-host pinned versions, CSP | Reduces trusted origins |
| Data exfiltration | CSP connect-src, minimal scripts on sensitive pages | Checkout gets fewest tags |
| Untrusted embeds | Sandboxed cross-origin iframe | Grant only needed capabilities |
| Heavy widgets | Facade, load on interaction | Video, maps, chat |
| Tracking without consent | Consent-gated loading | Legal and trust requirement |
| Main thread cost | async, defer, worker offloading | Load after main content |
| Unknown scripts | Inventory with owners and review | Required for PCI DSS 4 on payment pages |
Worked Example: SRI, a Sandboxed Embed, a Video Facade and Consent Gating
Each third party is loaded with the least privilege and the least cost that still delivers its value.
<!-- Pinned library with Subresource Integrity: a modified file is refused -->
<script src="https://cdn.jsdelivr.net/npm/dompurify@3.1.7/dist/purify.min.js"
integrity="sha384-BASE64_HASH_OF_THE_EXACT_FILE"
crossorigin="anonymous" defer></script>
<!-- Untrusted embed: scripts allowed, but no same-origin access, forms, popups or top navigation -->
<iframe src="https://widgets.partner.example/reviews?product=42"
sandbox="allow-scripts"
allow="clipboard-write"
loading="lazy" title="Customer reviews from Partner" width="600" height="400"></iframe>
<!-- Video facade: a thumbnail and button until the user asks for the player -->
<button class="video-facade" data-video-id="abc123" aria-label="Play product demo video">
<img src="/img/demo-thumb.avif" alt="" width="640" height="360">
</button>// Load the real player only on click
document.querySelectorAll<HTMLButtonElement>('.video-facade').forEach((btn) =>
btn.addEventListener('click', () => {
const iframe = document.createElement('iframe');
iframe.src = `https://www.youtube-nocookie.com/embed/${encodeURIComponent(btn.dataset.videoId!)}?autoplay=1`;
iframe.title = 'Product demo video';
iframe.allow = 'autoplay; encrypted-media; picture-in-picture';
iframe.width = '640'; iframe.height = '360';
btn.replaceWith(iframe);
}, { once: true }));
// Analytics loads only after consent, and never on the checkout route
export function loadAnalytics(consent: { analytics: boolean }) {
if (!consent.analytics || location.pathname.startsWith('/checkout')) return;
const s = document.createElement('script');
s.src = '/vendor/analytics-2.4.1.js'; // self-hosted pinned copy, covered by our CSP nonce strategy
s.async = true;
document.head.append(s);
}Generating the integrity hash with a command such as openssl dgst -sha384 -binary file.js piped into base64, or copying it from the CDN's page, and pinning the exact version is what makes SRI work: a floating URL such as the latest version would break as soon as the file changed.
Real-World Examples
- In 2018, Magecart attackers modified a third-party script used by British Airways' website and app to skim payment details, affecting about 380,000 transactions, and the UK Information Commissioner's Office fined the airline 20 million pounds for the breach.
- PCI DSS version 4.0 introduced requirements 6.4.3 and 11.6.1, effective from March 2025, which require merchants to inventory and authorize every script on payment pages, assure their integrity and detect unauthorized changes, directly addressing skimming through third-party scripts.
Review Questions & Answers
It makes the browser verify that a fetched script or stylesheet matches a known cryptographic hash, blocking files that were modified on a CDN or by a compromised provider. It only works for fixed, versioned files; scripts whose contents change without notice cannot use it.
The embedded content can run scripts but is treated as a unique opaque origin, so it cannot access the parent page, its own origin's cookies or storage, submit forms, open popups or navigate the top window. It can only communicate through postMessage.
A lightweight static stand-in, such as a thumbnail with a play button or a fake chat bubble, that looks like the widget. The real widget's heavy scripts load only when the user interacts with the facade, saving their cost for everyone who never uses it.
Every script on the page can read the card and personal details users type. Skimming attacks have repeatedly compromised third-party scripts on payment pages, so reducing their number reduces the attack surface, and standards such as PCI DSS 4 require strict control of them.