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.
HTML Imports are extremely useful and brings a lot of benefits to developers, some of them are:
HTML documents are imported with
link element. The default type
for resources loaded with import keyword is
<link rel="import" href="/path/to/headings.html">
For asynchronous imports use the
<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">
<script> var link = document.createElement('link'); link.rel = 'import'; link.href = '/path/to/headings.html'; document.head.appendChild(link); </script>
<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>
Currently only Chrome 36+ and Opera 23+ supports HTML imports.
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.
Join our mailing list and stay tuned! Never miss out news about Zino UI, new releases, or even blog post.