You can use HTML Imports to import an external HTML file with a <template>
element where you add the elements you want to import.
In the main file:
<head>
<link rel="import" href="template.html" id="myTemplate">
</head>
<body>
<div id="container"></div>
</body>
In the template.html
file:
<template>
<span>Hello World!</span>
</template>
<script>
//get the imported HTML document
var importedDoc = document.querySelector( '#myTemplate' ).import
//get the content of the template element
var content = importedDoc.querySelector( 'template' ).content
//add a compy to the main page
document.querySelector( '#container' ).appendChild( content.cloneNode( true ) )
</script>
In the example above, the conent of the <template>
element (the <span>
text "Hello World!"
) will be put in the <div id=container>
element in the main page.
Update 2019
HTML Imports won't be supported natively after Chrome 73. You should then use the other solutions listed above (the polyfill, an alternate module loader, JS import, or a direct download with fetch
).