include-fragment-element

<include-fragment> element

A Client Side Includes tag.

Installation

$ npm install --save @github/include-fragment-element

Usage

All include-fragment elements must have a src attribute from which to retrieve an HTML element fragment.

The initial page load should include fallback content to be displayed if the resource could not be fetched immediately.

import '@github/include-fragment-element'

Original

<div class="tip">
  <include-fragment src="/tips">
    <p>Loading tip…</p>
  </include-fragment>
</div>

On page load, the include-fragment element fetches the URL, the response is parsed into an HTML element, which replaces the include-fragment element entirely.

Result

<div class="tip">
  <p>You look nice today</p>
</div>

The server must respond with an HTML fragment to replace the include-fragment element. It should not contain another include-fragment element or the server will be polled in an infinite loop.

Other Attributes

accept

This attribute tells <include-fragment/> what to send as the Accept header, as part of the fetch request. If omitted, or if set to an empty value, the default behaviour will be text/html. It is important that the server responds with HTML, but you may wish to change the accept header to help negotiate the right content with the server.

loading

This indicates when the contents should be fetched:

Errors

If the URL fails to load, the include-fragment element is left in the page and tagged with an is-error CSS class that can be used for styling.

Events

Request lifecycle events are dispatched on the <include-fragment> element.

const loader = document.querySelector('include-fragment')
const container = loader.parentElement
loader.addEventListener('loadstart', () => container.classList.add('is-loading'))
loader.addEventListener('loadend', () => container.classList.remove('is-loading'))
loader.addEventListener('load', () => container.classList.add('is-success'))
loader.addEventListener('error', () => container.classList.add('is-error'))

Options

Attribute Options Description
src URL string Required URL from which to load the replacement HTML element fragment.

Deferred loading

The request for replacement markup from the server starts when the src attribute becomes available on the <include-fragment> element. Most often this will happen at page load when the element is rendered. However, if we omit the src attribute until some later time, we can defer loading the content at all.

The <details-menu> element uses this technique to defer loading menu content until the menu is first opened.

Patterns

Deferring the display of markup is typically done in the following usage patterns.

CSP Trusted Types

You can call setCSPTrustedTypesPolicy(policy: TrustedTypePolicy | Promise<TrustedTypePolicy> | null) from JavaScript to set a CSP trusted types policy, which can perform (synchronous) filtering or rejection of the fetch response before it is inserted into the page:

import IncludeFragmentElement from "include-fragment-element";
import DOMPurify from "dompurify"; // Using https://github.com/cure53/DOMPurify

// This policy removes all HTML markup except links.
const policy = trustedTypes.createPolicy("links-only", {
  createHTML: (htmlText: string) => {
    return DOMPurify.sanitize(htmlText, {
      ALLOWED_TAGS: ["a"],
      ALLOWED_ATTR: ["href"],
      RETURN_TRUSTED_TYPE: true,
    });
  },
});
IncludeFragmentElement.setCSPTrustedTypesPolicy(policy);

The policy has access to the fetch response object. Due to platform constraints, only synchronous information from the response (in addition to the HTML text body) can be used in the policy:

import IncludeFragmentElement from "include-fragment-element";

const policy = trustedTypes.createPolicy("require-server-header", {
  createHTML: (htmlText: string, response: Response) => {
    if (response.headers.get("X-Server-Sanitized") !== "sanitized=true") {
      // Note: this will reject the contents, but the error may be caught before it shows in the JS console.
      throw new Error("Rejecting HTML that was not marked by the server as sanitized.");
    }
    return htmlText;
  },
});
IncludeFragmentElement.setCSPTrustedTypesPolicy(policy);

Note that:

Relation to Server Side Includes

This declarative approach is very similar to SSI or ESI directives. In fact, an edge implementation could replace the markup before its actually delivered to the client.

<include-fragment src="/github/include-fragment/commit-count" timeout="100">
  <p>Counting commits…</p>
</include-fragment>

A proxy may attempt to fetch and replace the fragment if the request finishes before the timeout. Otherwise the tag is delivered to the client. This library only implements the client side aspect.

Browser support

Browsers without native custom element support require a polyfill. Legacy browsers require various other polyfills. See examples/index.html for details.

Development

npm install
npm test

License

Distributed under the MIT license. See LICENSE for details.