HTML Imports has been landed in some modern browsers.
So if you want to implement modern technology then you can do it with just writing some lines of code:
<link rel="import" href="import.html" onload="handleLoad(event)" onerror="handleError(event)">
onload
and onerror
are for logging the status of the page. (If the import page has been loaded or not.)
I've wrapped my import page (import.html
) into <template>
tag to clone it in a Javascript Variable.
import.html:
<template>
<h1>Hi there!</h1>
<h2>To use html-imports..</h2>
<h3>In Chrome 35 and below(in which you found the flag) you've to enable the flag: <span style="color: brown;">chrome://flags/#enable-html-imports</span></h3>
<h3>In Chrome 36 and Opera 23, it's supported by default. </h3>
</template>
You've to use Javascript to use the imported page
// Thanks to http://www.html5rocks.com/en/tutorials/webcomponents/imports/
var link = document.querySelector('link[rel="import"]');
// Clone the <template> in the import.
var template = link.import.querySelector('template');
var clone = document.importNode(template.content, true);
document.querySelector('#getting-started-info').appendChild(clone);
function handleLoad(e) {
console.log('Loaded import: ' + e.target.href);
}
function handleError(e) {
console.log('Error loading import: ' + e.target.href);
}
Variable link
is used to get the import element.
Variable template
is used to get the <template>
from the import.html
.
Variable clone
is used to get the content of the <template>
in import.html
.
Then I try to append the content to an ID of a <div>
.
handleLoad
and handleError
is used to notify the status of the import page via console which should be shown in many browsers' DevTools
.
I've written an article here.
And Made a repository in Github at github.com/krman009/html-imports.
html5rocks article.
I wish this will help you.