<iframe> embeds another HTML document with its own window object, cookies, and execution environment—think maps, chat widgets, PDF viewers, or isolated demos.
Essential attributes
src: nested document URL.title: accessible description for screen readers.sandbox: strips capabilities unless explicitly allowed.allow: delegates powerful APIs (camera, fullscreen).loading="lazy": defer offscreen iframes.
Security
- Third-party iframes execute scripts—audit vendors and use CSP.
sandboxtokens likeallow-scripts allow-same-originmust be justified—combining both can escape sandbox mitigations.
Privacy & performance
- Embedded players load large scripts—lazy load below the fold.
- Provide privacy-enhanced domains when regulations demand.
Operational blind spots
- Missing
titleon iframes—WCAG violations and confusing tab lists. - Infinite scroll inside iframes—focus traps escaping parent document are painful; test Tab cycles.
- Payment or PII widgets—verify CSP + sandbox tokens with security, not marketers’ embed snippets blindly.
Live demo — srcdoc + strict sandbox
No src URL—HTML is inline-escaped. Scripts are blocked unless you add allow-scripts (add carefully).
Important interview questions and answers
- Q: What is the practical difference between `id` and `class`?
A: `id` must be unique and is used for fragments/labeling; `class` is reusable for styling and behavior grouping. - Q: Why is `defer` commonly preferred for scripts?
A: It preserves HTML parsing, executes after parse, and avoids blocking rendering unlike classic synchronous scripts. - Q: How do `srcset` and `sizes` work together?
A: `srcset` provides candidate files and `sizes` tells expected rendered width so the browser can pick an optimal resource.
Pitfall: Sandboxed third-party iframes still need title attributes for accessibility.