HTML import is part of web component framework and its specification is in Draft stage. HTML import can be used to import another html document in current document. Currently only Chrome and Opera support it.
Here is sample code using HTML import
<h2>Imported stuff</h2> <div id="container"></div> <link id="import1" rel="import" href="/api/html-import-hello-world.html"> <script> var linkElement = document.querySelector('#import1'); var importedDoc = linkElement.import; var content = importedDoc.querySelector('#content'); document.querySelector('#container').appendChild(content.cloneNode(true)); </script>
Few points to note
- Imported document does not get inserted in current document’s html on its own. It has to be handled using Javascript.
-
We are using
linkElement.import
to get imported document object. -
To get dom element inside importedDoc, we are using
importedDoc.querySelector()
. After that we can clone these to insert in current page DOM.
Specification and Browser compatibility
Specification | Status | Categories |
---|---|---|
HTML Imports | W3C Working Draft | DOM, HTML5 |
Chrome | Firefox | IE | Edge | Safari | Opera |
---|---|---|---|---|---|
Yes 36+ | No | No | No | No | Yes 23+ |
Android Chrome | Android Firefox | iOS Safari | IE Mobile | Opera Mobile |
---|---|---|---|---|
Yes 47+ | No | No | No | Yes 33+ |
source: caniuse.com