@github/include-fragment-element

中文文档
6.4.1发布于 2025/09/04MITTypeScriptES Module零依赖构建来源已验证近 30 天下载 13.3万

A Client Side Includes tag.

原始使用文档
文档目录13 节
  1. Installation
  2. Usage
  3. Other Attributes
  4. Errors
  5. Events
  6. Options
  7. Deferred loading
  8. Patterns
  9. CSP Trusted Types
  10. Relation to Server Side Includes
  11. Browser support
  12. Development
  13. License

<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:

  • eager: Fetches and load the content immediately, regardless of whether or not the <include-fragment/> is currently within the visible viewport (this is the default value).
  • lazy: Defers fetching and loading the content until the <include-fragment/> tag reaches a calculated distance from the viewport. The intent is to avoid the network and storage bandwidth needed to handle the content until it's reasonably certain that it will be needed.

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.

  • loadstart - The server fetch has started.
  • load - The request completed successfully.
  • error - The request failed.
  • loadend - The request has completed.
  • include-fragment-replace (cancelable) - The success response has been parsed. It comes with event.detail.fragment that will replace the current element.
  • include-fragment-replaced - The element has been replaced by the fragment.
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

AttributeOptionsDescription
srcURL stringRequired 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.

  • A user action begins a slow running background job on the server, like backing up files stored on the server. While the backup job is running, a progress bar is shown to the user. When it's complete, the include-fragment element is replaced with a link to the backup files.

  • The first time a user visits a page that contains a time-consuming piece of markup to generate, a loading indicator is displayed. When the markup is finished building on the server, it's stored in memcache and sent to the browser to replace the include-fragment loader. Subsequent visits to the page render the cached markup directly, without going through a include-fragment element.

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:

  • Only a single policy can be set, shared by all IncludeFragmentElement fetches.
  • You should call setCSPTrustedTypesPolicy() ahead of any other load of include-fragment-element in your code.
    • If your policy itself requires asynchronous work to construct, you can also pass a Promise<TrustedTypePolicy>.
    • Pass null to remove the policy.
  • Not all browsers support the trusted types API in JavaScript. You may want to use the recommended tinyfill to construct a policy without causing issues in other browsers.

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.

  • Chrome
  • Firefox
  • Safari
  • Microsoft Edge

Development

npm install
npm test

License

Distributed under the MIT license. See LICENSE for details.

版本与发布记录

@github/include-fragment-element 共发布 25 个版本,首次发布于 2019/05/23;过去 12 个月发布了 0 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
6.4.1latest2025/09/041.2 年前
6.4.02025/05/201.5 年前
6.3.02023/06/163 年前
6.2.12023/06/163 年前
6.2.02023/06/163 年前
6.1.12022/12/203 年前

其他发布通道:next → 5.1.2-0。

关于 @github/include-fragment-element 的常见问题

@github/include-fragment-element 是什么?

A Client Side Includes tag.

如何安装 @github/include-fragment-element?

在项目目录运行 npm install @github/include-fragment-element,或使用 pnpm add / yarn add / bun add。

@github/include-fragment-element 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@github/include-fragment-element 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@github/include-fragment-element 可以商用吗?

@github/include-fragment-element 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@github/include-fragment-element 的下载量有多少?

根据 npm 官方下载统计,@github/include-fragment-element 在 2026/10/17 – 2026/11/15 这 30 天内被下载 132,768 次,日均约 4,426 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@github/include-fragment-element 还在维护吗?

最新版本 6.4.1 发布于 2025/09/04(1.2 年前);至今共发布 25 个版本,其中过去 12 个月发布了 0 个;首次发布于 2019/05/23。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。