Skip to content

Instantly share code, notes, and snippets.

@michaw
Created September 4, 2014 07:01
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 michaw/7cb11d7059642967f638 to your computer and use it in GitHub Desktop.
Save michaw/7cb11d7059642967f638 to your computer and use it in GitHub Desktop.
jQuery script for using HTMLImport as HTML templates
/**
* @author: Micha Wotton
* @version: 0.1
*
* To import an HTML file and inject it's content into a target container.
* Uses an additional data attribute on the 'link' element to identify target element.
* Format link tags as follows:
* <link type="import" href="path/to/import.html" dat-target="targetElementID">
*
* You can also use further imports within imported files. This script will recursively inject them,
* including into target elements in the parent document.
*/
$(document).ready(function(){
function importContent(links) {
links.each(function(e){
var target = $(this).data('target');
if (typeof target != 'undefined'){
var content = this.import;
$("#"+target).html($(content.body).html());
var childLinks = $(content).find("link[rel='import'");
if (childLinks.length > 0){
importContent(childLinks);
}
}
});
}
var links = $("link[rel='import'");
importContent(links);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment