Skip to content

Instantly share code, notes, and snippets.

@lukehedger
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lukehedger/91cdf1e783d3575d1965 to your computer and use it in GitHub Desktop.
Save lukehedger/91cdf1e783d3575d1965 to your computer and use it in GitHub Desktop.
HTML Imports/Templates example
<html>
<head>
<!-- Link to import file -->
<link rel="import" href="template.html" name="template1">
</head>
<body>
<!-- a container div with an id to match the name attribute of the import link -->
<div class="container" id="template1">
<!-- the contents of template.html will be inserted here at runtime -->
</div>
<!-- bit of JavaScript to insert the template -->
<script>
var imports = document.querySelectorAll('link[rel="import"]');
for (var i = imports.length - 1; i >= 0; i--) {
var template = imports[i].import.querySelector('template');
var clone = document.importNode(template.content, true);
var container = '#'+imports[i].getAttribute('name');
document.querySelector(container).appendChild(clone);
};
</script>
</body>
</html>
<template>
<div>
Markup goes here
</div>
</template>
@lukehedger
Copy link
Author

Quick example of using HTML Imports and HTML Templates together.

You can only use natively in Chrome 36+ but I've found them useful for quickly prototyping pages where I'll use a JavaScript templating library down the line.

There's also a Polymer polyfill if you want to go a step further.

Resource: HTML5 Rocks article on HTML Imports

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment