- Notifications
You must be signed in to change notification settings - Fork44
A client-side includes tag.
License
github/include-fragment-element
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
A Client Side Includes tag.
$ npm install --save @github/include-fragment-element
Allinclude-fragment
elements must have asrc
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
<divclass="tip"><include-fragmentsrc="/tips"><p>Loading tip…</p></include-fragment></div>
On page load, theinclude-fragment
element fetches the URL, the response is parsed into an HTML element, which replaces theinclude-fragment
element entirely.
Result
<divclass="tip"><p>You look nice today</p></div>
The server must respond with an HTML fragment to replace theinclude-fragment
element. It should not containanotherinclude-fragment
element or the server will be polled in an infinite loop.
This attribute tells<include-fragment/>
what to send as theAccept
header, as part of the fetch request. If omitted, or if set to an empty value, the default behaviour will betext/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.
This indicateswhen 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.
If the URL fails to load, theinclude-fragment
element is left in the page and tagged with anis-error
CSS class that can be used for styling.
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 withevent.detail.fragment
that will replace the current element.include-fragment-replaced
- The element has been replaced by the fragment.
constloader=document.querySelector('include-fragment')constcontainer=loader.parentElementloader.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'))
Attribute | Options | Description |
---|---|---|
src | URL string | Required URL from which to load the replacement HTML element fragment. |
The request for replacement markup from the server starts when thesrc
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 thesrc
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.
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.
You can callsetCSPTrustedTypesPolicy(policy: TrustedTypePolicy | Promise<TrustedTypePolicy> | null)
from JavaScript to set aCSP trusted types policy, which can perform (synchronous) filtering or rejection of thefetch
response before it is inserted into the page:
importIncludeFragmentElementfrom"include-fragment-element";importDOMPurifyfrom"dompurify";// Using https://github.com/cure53/DOMPurify// This policy removes all HTML markup except links.constpolicy=trustedTypes.createPolicy("links-only",{createHTML:(htmlText:string)=>{returnDOMPurify.sanitize(htmlText,{ALLOWED_TAGS:["a"],ALLOWED_ATTR:["href"],RETURN_TRUSTED_TYPE:true,});},});IncludeFragmentElement.setCSPTrustedTypesPolicy(policy);
The policy has access to thefetch
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:
importIncludeFragmentElementfrom"include-fragment-element";constpolicy=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.thrownewError("Rejecting HTML that was not marked by the server as sanitized.");}returnhtmlText;},});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 ofinclude-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.
- If your policy itself requires asynchronous work to construct, you can also pass a
- Not all browserssupport the trusted types API in JavaScript. You may want to use therecommended tinyfill to construct a policy without causing issues in other browsers.
This declarative approach is very similar toSSI orESI directives. In fact, an edge implementation could replace the markup before its actually delivered to the client.
<include-fragmentsrc="/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.
Browsers without nativecustom element support require apolyfill. Legacy browsers require various other polyfills. Seeexamples/index.html
for details.
- Chrome
- Firefox
- Safari
- Microsoft Edge
npm installnpm test
Distributed under the MIT license. See LICENSE for details.
About
A client-side includes tag.
Topics
Resources
License
Code of conduct
Security policy
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.
Uh oh!
There was an error while loading.Please reload this page.