Client side include feature for HTML

· GitHub ·

2 min read Original article ↗

Reference Implementation & Edge Case Handling in Userland

I've been exploring userland primitives for declarative HTML partial inclusion and created a zero-dependency Web Component, <html-include>, that addresses the primary architectural objections traditionally raised against client-side inclusions.

Key Edge Cases Addressed

1. CLS & FOUC Prevention

The component pre-injects its base block-level styles and allows authors to reserve layout geometry before the included content loads.

The min-height and aspect-ratio attributes help prevent Cumulative Layout Shift (CLS) and Flash of Unstyled Content (FOUC).

<html-include
  src="partials/header.html"
  min-height="116px"
>
  <div class="skeleton">Loading navigation...</div>
</html-include>

2. Table Contexts & Parser Eviction

HTML elements placed directly inside restricted parsing contexts such as <table>, <ul>, or <select> may be moved or removed by the browser's HTML parser through foster parenting and parser correction rules.

To handle these cases, the implementation supports an attribute-based fallback using data-include on valid host elements.

<table>
  <tbody data-include="partials/table-rows.html"></tbody>
</table>

This allows partial content to be loaded into elements that are valid within their surrounding HTML context.

3. Recursion Safeguards

The implementation detects circular and excessively deep inclusion chains before initiating additional network requests.

It traverses both regular DOM ancestors and Shadow DOM boundaries using ancestorChain() to:

  • Detect direct and indirect circular dependencies
  • Prevent infinite recursive inclusions
  • Enforce a configurable maximum nesting depth
  • Stop invalid requests before they reach the network layer

4. Script Execution & Content Security Policy

For security, <script> elements are stripped from included content by default.

Trusted first-party content can explicitly enable script execution using the allow-scripts attribute.

<html-include
  src="partials/dashboard.html"
  allow-scripts
></html-include>

When script execution is enabled, scripts are recreated and executed sequentially to preserve document order.

The implementation also supports Content Security Policy requirements by propagating valid CSP nonces when scripts are recreated.

5. Race Condition Prevention

The component uses AbortController to manage pending network requests.

When the src attribute changes dynamically, the previous request is cancelled before a new request begins.

const include = document.querySelector("html-include");

include.src = "partials/profile.html";
include.src = "partials/settings.html";

Without cancellation, a slower response from profile.html could arrive after settings.html and overwrite the newer content.

By aborting stale requests, the implementation ensures that only the latest requested partial is rendered.