//Karthik Srinivasan

Product Engineer, CTO & a Beer Enthusiast
Experiments, thoughts and scripts documented for posterity.

Quirky Personal Projects

LinkedIn

Email me

An Introduction to HTML Imports

July 2, 2016

HTML Imports are a way to include external HTML documents and web components on a page without making an Ajax request or loading an iframe. Because of this capability, HTML Imports may lead to better page load times as by default browsers cache import source files.

HTML Imports support DRY development. Here is an example. Imagine that you have three messages that are repeated on several web pages, perhaps even web pages on different domains. Rather than copying and pasting or retyping these messages for each page or project, they could be included using the HTML Imports feature.

Here is the HTML for a file called messages.html:

<div class="message-success">
    <h2>Success</h2>
    <p>Worked!</p>
</div>

<div class="message-failure">
    <h2>Failure</h2>
    <p>Failed!</p>
</div>

To reuse the content from messages.html, first include the document via HTML Imports. This amounts to adding a <link> element with its rel attribute set to "import" and its href pointed at messages.html, like this:

<link rel="import" href="messages.html">

Using JavaScript to accesses the imported messages.html document and loads the "success" message on the page. Each of the other messages could also be loaded in the same way or all together depending on how one wanted to use them. Here’s the code:

var htmlImport = document.querySelector('link[rel="import"]');
var htmlDoc = htmlImport.import;
var htmlMessage = htmlDoc.querySelector('.message-success');
document.body.appendChild(htmlMessage.cloneNode(true));

The success message is now included on the page, similar to how an Ajax request works.

There are polyfills that will make the feature available in nearly any browser. Perhaps, the most robust is the aforementioned Polymer Imports polyfill.