Skip to content

Instantly share code, notes, and snippets.

@olanod
Last active April 2, 2024 05:00
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save olanod/ede8befb771057bb004c4f57be591640 to your computer and use it in GitHub Desktop.
Save olanod/ede8befb771057bb004c4f57be591640 to your computer and use it in GitHub Desktop.
Simple template loader. A global object that loads and caches templates.
const templates = Object.create(null, {
load: {
value: async function(fileName) {
const url = new URL(fileName,
document.currentScript && document.currentScript.src || location.href)
if (url in this) return this[url]
// fetch and parse template as string
let template = await fetch(url)
template = await template.text()
template = new DOMParser().parseFromString(template, 'text/html')
.querySelector('template')
if (!template) throw new TypeError('No template element found')
// overwrite link tags' hrefs asuming they're always relative to the template
for (let link of template.content.querySelectorAll('link')) {
let href = document.importNode(link).href
href = new URL(href).pathname.substr(1)
link.href = new URL(href, url).href
}
document.head.append(template)
this[url] = template
return template
}
}
})
(async () => {
const template = await templates.load('my-template.html')
console.assert('my-template.html' in templates)
console.assert(template === document.head.lastElementChild)
console.assert(template instanceof HTMLTemplateElement)
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment