liveBook · Manning

HTML Imports

As explained in Web Components in Action

HTML Imports is a proposed, nonstandard web platform mechanism for importing an HTML document and its associated component resources into another document.

HTML Imports was a proposed mechanism for loading an HTML document containing a Web Component definition, template, and associated resources. It never became a broadly supported standard: Chrome was the only browser to implement it, and current versions deprecate it. section 7.1 section 15.0

A typical HTML Import-based component follows this sequence:

  • Load the HTML Imports polyfill and reference the component document with <link rel="import" href="samplecomponent.html">. section 7.1
  • Define the custom element in the imported document, usually alongside a <template> containing its markup and CSS. section 7.1
  • Wait for HTMLImports.whenReady(), obtain the imported owner document, clone template.content, and append the clone to the element. section 7.1
Listing 7.1. Using HTML Imports from a sample project
<html>
     <head>
        <title>HTML Import Demo</title>
        <script src="html-imports.min.js"></script>
        <link rel="import" href="samplecomponent.html"></link>      #1

        <style>
            button {
                background-color: #c09853;
            }
        </style>
     </head>

     <body>
          <sample-component></sample-component>                     #2
     </body>
</html>

The listing shows the complete host-page setup: polyfill loading, HTML-file import, and use of the resulting custom element. section 7.1

Imported component template

An imported component can place its behavior in samplecomponent.js and its reusable presentation in a template: a styled <span> is cloned from template.content and inserted into <sample-component>. section 7.1

How Web Components in Action covers it

How deep it goes
Explains import setup, readiness handling, owner documents, template cloning, and insertion, but stops short of standard adoption.
Examples
Uses an imported sample component with a styled template, cloned content, and a custom <sample-component> element.
What it assumes
Assumes familiarity with HTML, DOM elements, custom elements, templates, and JavaScript classes.
What you can do after
Apply HTML Imports through a polyfill to load an HTML component and populate it by cloning its template.
How it connects
Connects HTML Imports with Web Components, Custom Elements, HTML templates, Shadow DOM, and JavaScript modules.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Web Components in Action. The section links point to the parts of the book it draws on.