Embeddable Widget Design: Script vs Iframe, Shadow DOM and postMessage
Saket Bhatnagar, Founder, SevyDevy, Last updated , 22 min read
Summary
- An embeddable widget is a small piece of your product, such as a reviews box, that other websites add by pasting one script tag you give them.
- Your code runs inside a stranger's page, called the host page. Its styles can break your widget, and your script can slow its loading or make its layout jump.
- You protect both sides with isolation. Shadow DOM, a private, hidden branch of the page's elements with its own styles, blocks most outside CSS. An iframe, a page inside a page, served from your own origin isolates code and storage as well.
- Iframe and host talk through postMessage, a browser method for sending data between windows. Always name the receiver's exact origin and check event.origin, the sender's site, on every message.
- Beginners can stop after the section on script vs iframe embeds. Engineers get Chromium 153 test results after that, such as silently dropped messages and inherited styles leaking into Shadow DOM. In a desktop-sized test window, one late box scored 0.195 on layout shift, a measure of content jumping around. The good limit is 0.1.
What goes wrong when you paste a third-party widget into someone else's page?
An embeddable widget runs your code on a page you do not control. The page can break your widget, and your widget can hurt the page. Both failures happen in front of the host site's users.
Picture a common setup. A small startup sells a product reviews service to online shops across India. A shop pastes one script tag, and a star-rating box appears under each product. The setup is made up, but each failure below was reproduced in a real browser.
In the first week, three tickets arrive. One shop's global button style turns the widget's buttons bright red with 30 pixels of padding. Another shop's product photo jumps down the screen when the reviews box loads above it. A third shop's security team asks why the widget accepts messages from any website.
Each ticket is a different problem with an embeddable widget: style leaks, layout shift and an unsafe message channel. This guide follows that one reviews widget and fixes all three. Every fix comes with a way to check it worked.
Which words do you need before building an embeddable widget?
You need six words: host page, origin, iframe, Shadow DOM, postMessage and Core Web Vitals. Each one gets a plain meaning and a link to the reviews widget.
- Host page: the website that pastes your widget in. For the reviews widget, it is each shop's product page.
- Origin: the scheme, host name and port of a page, such as https, shop.example and 443. Two pages have the same origin only when all three match.
- Iframe: an element that shows a whole separate web page inside the current one. If the inner page has a different origin, the two pages cannot read each other's code or data.
- Shadow DOM: a hidden subtree of elements attached to one element on the page. Styles inside it stay inside, and most page styles do not reach in.
- postMessage: a browser method that sends a copy of some data from one window to another, even across origins. The receiving window gets a message event.
- Core Web Vitals: three measurements of how a page feels to users, covering loading speed, response to taps and layout stability. They are explained with numbers further down.
What is an embeddable widget, and how does it load on a host page?
An embeddable widget is code that you host and other sites run by adding a small snippet to their pages. The snippet loads your main script, and that script draws your interface inside the host page.
Most widgets follow the same three-part path. The host pastes a tiny loader snippet once. The snippet adds your real script, often called loader.js, from your server or CDN, a network of servers that sends files from near the user. That script then builds the visible widget.
The last step is the big design choice. The widget can draw itself straight into the host page, usually inside a Shadow DOM. Or it can create an iframe that loads a page from your own origin. Many real widgets mix both.
How the reviews widget gets onto a shop's page
Drag to exploreNotice that only the snippet is pasted by the shop. Everything after it is your code, running inside their page.
Diagram connections:
- Shop product page to Loader snippet (runs)
- Loader snippet to loader.js on your CDN (adds async script)
- loader.js on your CDN to Need code isolation?
- Need code isolation? to Shadow DOM widget (No)
- Need code isolation? to Iframe widget (Yes)
- Shadow DOM widget to Reviews API (fetch ratings)
- Iframe widget to Reviews API (fetch ratings)
- Shop product page: The host page; you do not control it
- Loader snippet: A few lines the shop pastes once
- loader.js on your CDN: Your main script, fetched without blocking
- Need code isolation?: Payments, logins or untrusted content
- Shadow DOM widget: Drawn in the host page, private styles
- Iframe widget: A page from your origin inside theirs
- Reviews API: Your server that returns ratings
A useful picture is a guest in someone's home. A script widget is a guest who walks through every room. Shadow DOM is that guest staying behind a screen in the living room. An iframe is a guest in a locked room who passes notes under the door.
Those notes are postMessage, and reading the sender's name on each note is the origin check. Where the picture breaks: a screen still lets some things through. Inherited styles such as font and text colour cross into Shadow DOM, as the tests below show.
Script embed vs iframe embed: which should you choose?
Choose a script embed with Shadow DOM when the widget must feel part of the page and handles no secrets. Choose an iframe when the widget handles logins, payments or anything the host page must not read.
A script embed runs with the host page's full powers. It can read the page, and the page can read it. That is simple and fast, but nothing protects either side from the other's code.
An iframe from your own origin is a separate document. The host page cannot reach into it, and the browser keeps its storage apart. The cost is a second page load and a message channel for every interaction.
| Question | Script embed with Shadow DOM | Iframe embed from your origin |
|---|---|---|
| Who can read the widget's data? | Any script on the host page | Only your page; the host cannot read it |
| Do host CSS rules reach in? | Most do not; inherited ones like font do | No; it is a separate document |
| Can it size itself to its content? | Yes, it is part of the page flow | Only if it sends its height by postMessage |
| Extra load cost | One script | A full page: HTML, CSS and script |
| Good fit | Rating stars, share buttons, badges | Checkout, login, chat with user data |
For the reviews widget, the star display is a script embed in Shadow DOM. The write-a-review form needs the reviewer's login, so it opens in an iframe. Beginners can stop here. The next sections test each claim in Chromium 153 as of 30 October 2026.
How do you stop host page CSS from breaking your widget?
Put the widget's elements inside a Shadow DOM and keep its stylesheet there too. Page selectors then stop matching your elements, and your selectors stop matching theirs.
The naive first try is to give every class a long prefix, such as reviews-widget-button. That does not stop a host rule written for every button element. The first ticket was exactly that kind of rule.
What the test showed
We built a host page with three rules. Buttons got a red background and 30 pixels of padding. A title class got upper-case text. The body got green text in the Georgia font.
We then attached an open shadow root, put a button and a paragraph inside, and read the computed styles in Chromium 153.
- The host button rule did not reach the widget's button. Its background was the widget's own blue, and its padding stayed at the 1 pixel default.
- The host title class did not reach in, and the widget's own title class did not leak out to the host button.
- The body's green colour and Georgia font did reach the widget's paragraph. Inherited properties pass from the host element into the shadow tree.
- A plain document.querySelectorAll for buttons found only the host's one button, not the widget's.
Resetting inherited styles
Add a rule for the :host selector, which targets the element the shadow root hangs on, that sets all: initial. In our test, this reset the paragraph to black text in the browser's default font. Then set your own font and colours on top.
You do not always want that reset. Inheriting the shop's font can make the widget look native. Decide per property, and write the choice down for your support team.
Open vs closed shadow roots
A closed shadow root hides itself from page scripts: the shadowRoot property returns null. Our test confirmed null for closed mode. MDN warns that closed mode is not a strong security mechanism, because browser extensions and other tricks can get around it.
When should the widget live in an iframe instead?
Use an iframe served from your own origin when the widget shows private data or takes user input you must protect. The browser then keeps the host page out of your document and your storage.
If you embed content you do not fully trust, add the sandbox attribute as well. An empty sandbox applies every restriction: no scripts, no forms, no pop-ups. Each token you add, such as allow-scripts, lifts one restriction.
One catch for logins: as of 30 October 2026, MDN notes that browsers commonly block third-party cookies inside cross-site frames. So your iframe may not see the login cookie your main site set. The Storage Access API lets the frame ask for that access, so test it in every browser you support.
What sandboxing changed in the test
We loaded a frame with sandbox set to allow-scripts only. Inside it, both localStorage and document.cookie threw a SecurityError. Its own origin read as the string null, and so did event.origin on the messages it sent.
That matches the HTML Living Standard: a sandboxed frame is treated as a unique opaque origin unless allow-same-origin is given. The practical lesson is simple. Never write an origin check that accepts null, because any sandboxed frame anywhere can send it.
Two more iframe settings worth a line each
- Give every iframe a title, such as Product reviews. MDN notes that screen reader users rely on it to know what the frame contains.
- Use the allow attribute to grant only the browser features you need, such as camera access. MDN says it adds limits on top of the page's Permissions-Policy header rather than replacing it.
- Serve the widget pages with a Content-Security-Policy frame-ancestors header listing the shops allowed to frame them. MDN notes it cannot be set in a meta element.
How do you design a safe postMessage contract between widget and host?
Treat postMessage as a public API with three rules. Send only to the exact origin you expect. Accept only from the exact origin and window you expect. Accept only message shapes you have defined, with a version number.
A contract here means a written list of message types, their fields and who may send each one. For the reviews iframe, there is one message: reviews:resize, sent by the iframe, carrying its content height. Without it, the iframe would stay at a fixed height and cut off long reviews.
One resize message, checked on both ends
Drag to exploreLook at the two gates: the sender names the receiver's origin, and the receiver checks origin, source and shape before acting.
Diagram connections:
- Measure content height to postMessage to host (height in pixels)
- postMessage to host to Origin matches?
- Origin matches? to Message discarded (No)
- Origin matches? to Host checks the message (Yes)
- Host checks the message to Resize iframe (all checks pass)
- Measure content height: Iframe → itself, on every resize
- postMessage to host: Iframe → host, targetOrigin is the shop
- Origin matches?: Browser → host; mismatch is dropped silently
- Message discarded: Browser → nobody; no error is thrown
- Host checks the message: Host → itself: origin, source, type, version
- Resize iframe: Host → iframe element, height clamped
The sending side
Inside the iframe, the widget measures its own height and posts it to the parent window. The second argument, targetOrigin, is the host's exact origin. The loader passed it in the iframe URL, and your server checked it against the shop's allowed domains.
// Runs inside the iframe, on https://widgets.example
// The server already checked 'host' against this site's allowed domains.
var HOST_ORIGIN = new URLSearchParams(location.search).get('host');
function reportHeight() {
parent.postMessage({
type: 'reviews:resize',
v: 1,
height: document.documentElement.scrollHeight
}, HOST_ORIGIN);
}
new ResizeObserver(reportHeight).observe(document.body);The receiving side
On the host page, loader.js creates the iframe and listens for messages. It ignores anything not from your origin, not from that exact frame, or not shaped like a version 1 resize message. It also clamps the height between 100 and 2,000 pixels.
// Runs on the host page, inside loader.js
var WIDGET_ORIGIN = 'https://widgets.example';
var mount = document.querySelector('#reviews');
var frame = document.createElement('iframe');
frame.src = WIDGET_ORIGIN + '/reviews?site=demo-123&host=' +
encodeURIComponent(location.origin);
frame.title = 'Product reviews';
frame.style.cssText = 'width:100%;height:320px;border:0';
mount.appendChild(frame);
window.addEventListener('message', function (event) {
if (event.origin !== WIDGET_ORIGIN) return;
if (event.source !== frame.contentWindow) return;
var msg = event.data;
if (!msg || msg.type !== 'reviews:resize' || msg.v !== 1) return;
var h = Number(msg.height);
if (!Number.isFinite(h)) return;
frame.style.height = Math.min(Math.max(h, 100), 2000) + 'px';
});Both code blocks ran in Chromium 153, with local origins swapped in for the example domains. The frame reported 337 pixels and the host resized it. A fake resize message posted from the host window itself was ignored.
In a separate test, a second frame from the same widget origin sent a height of 9,999. The host ignored it because event.source was not the expected frame. A frame-ancestors header naming only the shop also made Chromium refuse to load the widget inside an unlisted site.
What just happened?
- A message sent with the wrong targetOrigin never arrived, and the postMessage call did not throw. The HTML standard says such messages are discarded to avoid leaking data.
- A message sent with targetOrigin set to the star character arrived. It would also reach any other site loaded in that window by then, which is why MDN says to name the exact origin.
- event.origin carried the sender's exact origin with scheme and port. Comparing it with !== against one fixed string is the whole check.
How should a widget script load: async, defer or dynamic insertion?
Load it so it never blocks the host page from parsing. In practice, that means a script element added by the snippet, which behaves like async, or a plain async attribute.
A normal script element without either attribute stops the browser from reading the rest of the page until the script downloads and runs. web.dev notes that a slow third-party server can then hold up rendering for a long time.
We tested the three options in Chromium 153 with deliberate delays on the server. Each script logged its name when it ran. A slow script took 400 milliseconds to arrive and a fast one took 50.
| How the script is added | Blocks parsing while downloading? | When it runs | Order kept? |
|---|---|---|---|
| No attribute | Yes | As soon as it arrives, before later HTML is read | Yes, document order |
| async attribute | No | As soon as it arrives, possibly before parsing ends | No; fast ran before slow |
| defer attribute | No | After parsing, before DOMContentLoaded | Yes; slow ran before fast |
| Added by a script | No | As soon as it arrives | No; its async property was true |
DOMContentLoaded is the event that fires once the browser has read the whole HTML. Deferred scripts ran just before it, in the order they were written. Async scripts can still pause parsing for the moment they execute, as web.dev points out.
The loader snippet
A widget usually ships a snippet like the one below. It creates a small queue function, adds the real script with async set, and records commands until that script arrives. When loader.js runs, it replays the queue.
(function (w, d) {
w.Widget = w.Widget || function () {
(w.Widget.q = w.Widget.q || []).push(arguments);
};
var s = d.createElement('script');
s.src = 'https://widgets.example/v1/loader.js';
s.async = true;
d.head.appendChild(s);
})(window, document);
Widget('init', { siteId: 'demo-123', mount: '#reviews' });We ran this snippet with a loader that took 300 milliseconds to arrive. In our runs, DOMContentLoaded fired within 70 milliseconds, before the widget existed. The queued init call was then replayed once, and the reviews rendered inside a shadow root.
How do you keep the host page's Core Web Vitals healthy in 2026?
Reserve the widget's space before it loads, keep its start-up work in small pieces, and load heavy parts only when needed. Each habit mainly protects one of the three Core Web Vitals.
web.dev defines the three, with good thresholds as of 30 October 2026. Largest Contentful Paint (LCP), when the main content appears, should be 2.5 seconds or less. Interaction to Next Paint (INP), how fast the page responds to taps, should be 200 milliseconds or less.
Cumulative Layout Shift (CLS), how much visible content jumps around, should be 0.1 or less. Each target is checked at the 75th percentile of page loads, meaning three in four visits must meet it.
Layout shift: reserve the space
This was the second ticket. We built a page where a widget inserted a 250 pixel box above the article after 800 milliseconds. In a 1,280 by 720 pixel window, Chromium's layout-shift entries added up to 0.1953, nearly double the 0.1 limit.
The score depends on screen size. In a 390 by 844 phone-sized window, the same insert scored 0.2962. These are lab numbers from single page loads, not CLS measured from real visits.
We then gave the empty slot a min-height of 250 pixels before the widget arrived. The same insert scored 0.0000. web.dev recommends this, or the aspect-ratio property for responsive boxes, and warns against collapsing the space if loading fails.
For the reviews widget, the loader sets a min-height on the mount element at once, sized to a typical review list. Any later growth from the resize message still moves content below it and counts towards CLS. So size the reserved box close to the usual final height.
Responsiveness: no long tasks at start-up
A long task is any piece of main-thread work longer than 50 milliseconds, per web.dev. While it runs, the page cannot respond to taps, which hurts INP.
In our test, a widget that did 200 milliseconds of set-up in one go produced one 200 millisecond long task. Splitting the same work into ten 20 millisecond chunks, with a setTimeout of 0 between them, produced none.
web.dev also describes scheduler.yield, which resumes your work ahead of other queued tasks. As of 30 October 2026, web.dev lists it in Chrome 129, Edge 129 and Firefox 142, but not Safari. So keep a setTimeout fallback.
Loading: only fetch what the user will use
- Use loading=lazy on the iframe. MDN says the browser then waits until the frame is near the visible area, and only when JavaScript is enabled.
- Use a facade for heavy widgets: a static look-alike that loads the real widget on click. Chrome's docs show a 3 KB video facade standing in for a 540 KB player.
- Add a preconnect hint only for origins needed early. web.dev says unused connections close after 10 seconds, and suggests dns-prefetch for less important origins.
- Set a size budget for your widget and measure it on every release. web.dev advises site owners to pick vendors that send the least code.
How do you check a widget is a good guest before shipping?
Run the same checks a careful shop would run, on a test host page with hostile CSS. Each step below names what to look for, so you know it passed.
Add a hostile stylesheet
Style every button, paragraph and div on the test page with loud colours and large padding. Your widget should look unchanged, except for any inherited fonts you chose to allow.
Throttle your CDN
Delay loader.js by several seconds in your test server. The host content should still appear first, and DOMContentLoaded should fire before your widget exists.
Measure layout shift
Observe layout-shift entries with a PerformanceObserver while the widget loads. The total from your widget should be 0, not a number like 0.19.
Watch for long tasks
Observe longtask entries during start-up. Any entry means some piece of your work ran over 50 milliseconds and needs splitting.
Fire bad messages
From a second origin and from a sandboxed frame, post messages that look like yours. Your host listener should ignore all of them, including those with origin null.
Turn your CDN off
Block the widget's domain entirely. The page should still work. The reserved box should keep its size, ideally showing a short fallback line from the shop's own markup.
How do you explain embeddable widget design in a system design interview?
Frame it as two-way protection: protect the widget from the page and protect the page from the widget. Then walk through loading, isolation, messaging and performance in that order.
State the constraint
Say the widget runs on pages you do not control, with unknown CSS, scripts and security policies. Every later choice follows from that.
Describe loading
A small snippet adds an async loader from a CDN and queues commands. The host page does not wait for your servers to respond.
Pick isolation per feature
Display parts go in Shadow DOM for style isolation. Anything with logins, payments or private data goes in an iframe from your origin.
Define the message contract
List each postMessage type with a version. Senders name the exact target origin; receivers check origin, source and shape, and never accept null.
Protect the vitals
Reserve space to keep CLS near zero, split start-up work to avoid long tasks, and lazy-load or use a facade for heavy parts.
Cover failure and rollout
Mention a versioned script URL, a frame-ancestors allow-list per customer, and what the host sees when your CDN is down.
Questions people ask
Is Shadow DOM enough to secure an embeddable widget?
No, Shadow DOM isolates styles, not code or data. Any script on the host page runs in the same window, so it can read your widget's elements and replace built-in functions your code calls, such as fetch. Even a closed shadow root is not a strong barrier, as MDN notes. Use an iframe from your own origin for anything secret, such as logins or payment details.
Why does my postMessage never arrive?
Usually the targetOrigin you passed does not exactly match the receiver's origin. Scheme, host name and port must all match, so http vs https or a missing www is enough. The browser drops the message silently and the postMessage call does not throw. Log the target origin while testing and compare it with the receiver's location.origin.
Can I use the star character as the targetOrigin?
Only for data that is safe for any website to read. The star tells the browser to deliver the message whatever page is now in that window. If the window has been navigated elsewhere, a stranger gets your data. The HTML standard says not to use it for confidential information, and MDN says to name the exact origin.
Should a widget script use async or defer?
Use async, or add the script from a snippet, for a widget that should start as soon as possible without blocking parsing. Use defer when the widget is less urgent and must run in order after parsing. Never add a plain blocking script element from a third-party server, because a slow server then holds up the whole page.
How do I stop the host page's font leaking into my widget?
Add a rule for the :host selector inside your shadow root that sets all: initial, then set your own font. Inherited properties such as font-family and color cross the shadow boundary from the host element. Our Chromium 153 test showed the reset returned text to the browser default before the widget's own styles applied.
Does an iframe widget hurt Core Web Vitals less than a script widget?
Not automatically. An iframe still downloads a full page and can still shift layout if its height changes after load. It does keep its own scripts off the host's DOM. Reserve its space, lazy-load it when it sits below the fold, and size the reserved box close to the final height so resize messages change it very little.
Keep learning
Practise it with Lala
A question on this guide, hints and a review.
Read next
Sources (14)
- MDN: Window postMessage() method
- HTML Living Standard: cross-document messaging
- HTML Living Standard: the iframe element, sandbox and loading attributes
- MDN: the iframe element reference (sandbox, loading, allow, title)
- MDN: Storage Access API (third-party cookies in embedded frames)
- MDN: Using shadow DOM
- MDN: the script element reference (async, defer, integrity)
- MDN: CSP frame-ancestors directive
- web.dev: Efficiently load third-party JavaScript
- web.dev: Third-party JavaScript performance
- web.dev: Web Vitals (LCP, INP and CLS thresholds)
- web.dev: Optimize Cumulative Layout Shift
- web.dev: Optimize long tasks
- Chrome for Developers: Lazy load third-party resources with facades