Categories

HTML Imports

Posted on: August 6, 2015 by Dimitar Ivanov

Specification

HTML Imports are HTML documents that are linked as external resources from other HTML documents. HTML Imports alongside Custom Elements, Shadow DOM and HTML Templates are part of Web Components set of standards. In short HTML Imports are a way to include and reuse HTML documents in other HTML documents. They are much alike to PHP include statement. Imported documents can include markup, styles, scripts, events, templates, custom elements, or anything else that regular HTML document can contain.

Why HTML Imports?

HTML Imports are extremely useful and brings a lot of benefits to developers, some of them are:

  • Reusability
  • Encapsulation
  • Syndication

Loading imports

HTML documents are imported with link element. The default type for resources loaded with import keyword is text/html.

<link rel="import" href="/path/to/headings.html">

For asynchronous imports use the async attribute.

<link rel="import" href="/path/to/headings.html" async>

In order to import documents from another domain you must implement CORS mechanism to avoid restrictions provided by same-origin policy.

<link rel="import" href="https://www.example.com/path/to/headings.html">

Creating imports

Alternatively HTML imports could be loaded programmatically with Javascript:

<script>
var link = document.createElement('link');
link.rel = 'import';
link.href = '/path/to/headings.html';
document.head.appendChild(link);
</script>

Using the content

For example headings.html contains:

<h1>Heading 1</h1>
<h2>Heading 2</h2>
<h3>Heading 3</h3>
<h4>Heading 4</h4>

Let's say that our home page index.html imports the headings and use some of them. See working demo.

<!DOCTYPE html>
<html>
    <head>
        <link rel="import" href="/path/to/headings.html">
    </head>
    <body>
        <script>
            var link = document.querySelector('link[rel="import"]');
            var headings = link.import;
            var h1 = headings.querySelector('h1');
            document.body.appendChild(h1.cloneNode(true));
        </script>
    </body>
</html>

Browser support

Currently only Chrome 36+ and Opera 23+ supports HTML imports.

Polyfills

Since HTML imports are not vastly supported by current browsers you should consider using a polyfills as Web Components or Polymer.

More Web Components
References
Share this post

If you have questions about html import or web components itself, drop a comment below. And do not forget to share this blog post. Thanks for reading.


0 Comments

Leave a comment

Captcha