Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Custom HTML Templating
- // usage: IE11-friendly DOM templating for simple repeated HTML
- // example: <script type=text/html data-template-name="demo">
- window.templates = window.templates || {}
- // Store a DOM fragment of the template at window.templates[name]
- function readTemplateFromTag(tag) {
- return loadTemplate(tag.dataset.templateName, tag.textContent)
- }
- // Load a template from a string
- function loadTemplate(name, content) {
- window.templates[name] = document.createDocumentFragment()
- Array.prototype.slice.call(
- new DOMParser()
- .parseFromString(content, 'text/html')
- .body
- .children
- ).forEach(function(child) {
- return window.templates[name].appendChild(child)
- })
- }
- // Populate a tag with the children of window.templates[name]
- function mountTemplate(string, tag, preflight, postflight) {
- var template = document.querySelector(
- 'script[type="text/html"][data-template-name="'
- + string
- + '"]'
- )
- readTemplateFromTag(template)
- if (preflight) {
- preflight(window.templates[string])
- }
- Array.prototype.slice.call(window.templates[string].childNodes)
- .forEach(function(child) {
- if (
- // tag is <style> or <script>
- (
- child.tagName.toLowerCase() === 'script'
- || child.tagName.toLowerCase() === 'style'
- )
- && (
- (
- // tag has textContent, and is already present in the document
- (
- child.textContent !== ''
- && Array.prototype.slice.call(document.getElementsByTagName(child.tagName.toLowerCase())).some(function(node) {
- return node.textContent === child.textContent
- })
- )
- // tag has src="", and is already present in the document
- || (
- child.src !== undefined
- && document.querySelector(child.tagName + '[src="' + child.src + '"]')
- )
- )
- )
- ) {
- false
- } else {
- tag.appendChild(child.cloneNode(true))
- }
- })
- if (postflight) {
- postflight(tag)
- }
- }
- // Automatically mount named templates
- // usage: Populate matching template into any tag with data-template attribute
- // example: <custom-element data-template="demo">
- function autoMount() {
- return Array.prototype.slice.call(document.querySelectorAll('[data-template]'))
- .forEach(function(tag) {
- return mountTemplate(tag.dataset.template, tag)
- })
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement