include-file
Load remote HTML fragments with progressive enhancement. Fallback content shows until fetch completes.
Overview
The <include-file> component fetches HTML from a URL and injects it. Any existing content serves as a fallback shown until the fetch completes (or if it fails).
<include-file src="/partials/header.html"> <p>Loading header...</p></include-file>
Attributes
| Attribute | Values | Default | Description |
|---|---|---|---|
src | string | — | URL to fetch HTML from |
mode | "replace", "append", "prepend" | replace | How fetched content is inserted |
lazy | boolean | — | Defer loading until element enters viewport |
allow-scripts | boolean | — | Re-execute inline scripts in loaded content (trusted sources only) |
Lazy Loading
Add lazy to defer the fetch until the element scrolls into view (with a 200px root margin).
<!-- Only loads when scrolled into view --><include-file src="/partials/comments.html" lazy> <p>Comments loading...</p></include-file>
Insert Modes
Control how the fetched HTML is inserted with mode.
<!-- Replace (default) --><include-file src="/partials/content.html" mode="replace"></include-file> <!-- Append to existing content --><include-file src="/partials/more.html" mode="append"> <p>Existing content stays.</p></include-file> <!-- Prepend before existing content --><include-file src="/partials/banner.html" mode="prepend"> <p>This moves down.</p></include-file>
Events
| Event | Detail | Description |
|---|---|---|
include-file:loaded | { src, html } | Fired after successful content load |
include-file:error | { src, error } | Fired if fetch fails |
const include = document.querySelector('include-file'); include.addEventListener('include-file:loaded', (e) => { console.log('Loaded:', e.detail.src);}); include.addEventListener('include-file:error', (e) => { console.error('Failed:', e.detail.error);});
JavaScript API
| Method | Description |
|---|---|
reload() |
Re-fetch content from the current src. |
Progressive Enhancement
Without JavaScript, the fallback content (whatever HTML is inside the element) remains visible. The src URL is never fetched, so users see the fallback. This makes it safe to use for non-critical content.
Accessibility
- Fallback content ensures content is always available.
- Error state sets
data-erroron the element. The original fallback content is restored on first-load failure. Style[data-error]in CSS to show a visible error state. - Changing the
srcattribute triggers a re-fetch, enabling dynamic content updates.
Trust Boundary
This component injects HTML via innerHTML. It is designed for loading trusted first-party fragments (partials, includes from your own server). Do not use it to load untrusted or user-generated HTML from third-party sources.
The allow-scripts attribute is an additional opt-in that re-executes inline scripts in loaded content. Only use it when you control the source URL.
Related
<iframe>— Embeds an entire document (heavier, sandboxed)