Last active
November 30, 2016 19:12
-
-
Save liddiard/9a8215fb6e89c028c5422c982a5aaa38 to your computer and use it in GitHub Desktop.
Load a handlebars template into the DOM with no additional code. Gets the template URL from script's `data-template` attribute, and JSON template data URL from `data-context` attribute.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function(){ | |
// get a reference to the current script (IE support) | |
// http://stackoverflow.com/a/22745553 | |
const scripts = document.getElementsByTagName('script'); | |
const currentScript = scripts[ scripts.length - 1 ]; | |
const CONTEXT_URL = currentScript.dataset.context; | |
const TEMPLATE_URL = currentScript.dataset.template; | |
if (!CONTEXT_URL || !TEMPLATE_URL) { | |
console.error('Missing `context` or `template` data attributes.'); | |
} | |
else { | |
get(CONTEXT_URL, function(data) { | |
const context = JSON.parse(data); | |
get(TEMPLATE_URL, function(source) { | |
// http://handlebarsjs.com/#getting-started | |
const template = Handlebars.compile(source); | |
const html = template(context); | |
const app = document.createElement('div'); | |
app.id = 'app'; | |
app.innerHTML = html; | |
// insert the compiled html after the script tag | |
// http://stackoverflow.com/a/4793630 | |
currentScript.parentNode.insertBefore(app, currentScript.nextSibling); | |
}); | |
}); | |
} | |
function get(url, callback) { | |
var r = new XMLHttpRequest(); | |
r.open('GET', url); | |
r.onreadystatechange = function() { | |
if (r.readyState !== 4 || r.status !== 200) return; | |
else callback(r.responseText); | |
}; | |
r.send(); | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment