Declarative client-side transclusion with h-include


Nicolás Delfino / September 12, 2020

2 min read

Declarative Client-Side Transclusion

h-include is a javascript library for including fragments client side (client side transclusion), perfect fit for micro-frontend architecture in combination with server-side transclusion technologies like Edge-Side Includes.

In its most basic, h-include is simply a custom element that accepts a src attribute which it will use to fetch content through AJAX, then depending on the outcome of that call, it will transclude the content of the ajax response into itself.


The outcome of the attempted inclusion is represented in class attributes included_(req status)


H-Include Types#

h-include ships with different types out of the box, here´s a short description of what they are

Includes the HTML resource when element enters the viewport (Intersection Observer)
Request an HTML resource and include all found scripts and stylesheet references
Like h-import + Intersection Observer
h-import requires loadjs to be available on the window object
link events are captured by the element itself, changes the src attribute and triggers a refresh

Advanced Usage#

conditional inclusion using WHEN

Since I started using h-include at a client I've gotten more involved in the project and have made some contributions that further mimics the esi spec, one of them being the usage of WHEN and WHEN-FALSE-SRC

Inclusion Based on Predicate


Unlimited Namespacing

The predicate function supports namespacing meaning you could have different predicates per project

request errors and alternative inclusion using WHEN-FALSE-SRC

WHEN-FALSE-SRC can also be used not only as a backup for when the predicate returns false but also to handle request errors


Extending H-Include#

Extending h-include to handle different use cases is quite simple to do, for instance - if we imagine needing an h-include element that adds a date as a data attribute to the included element - we could extend the H-include element prototype and override the connected callback method.

window.HInclude.HincludeDateElement = (function () {
  var proto = Object.create(HInclude.HIncludeElement.prototype);
  var addDate = function (element) {
    element.setAttribute('data-date', new Date());

  proto.connectedCallback = function () {

  var HincludeDateElement = function () {
    return Reflect.construct(HTMLElement, arguments, HincludeDateElement);
  HincludeDateElement.prototype = proto;

  Elements.define('h-include-date', HincludeDateElement);
  return HincludeDateElement;


The h-include library refered in this article is written by Gustaf Nilsson Kotte and is based on hinclude.js by @mnot. Make sure to checkout the github repo if this sounds interesting, there's alot more that I haven't mentioned in this article.