Advertisement
Guest User

Untitled

a guest
Apr 18th, 2019
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.40 KB | None | 0 0
  1. // Custom HTML Templating
  2. // usage: IE11-friendly DOM templating for simple repeated HTML
  3. // example: <script type=text/html data-template-name="demo">
  4. window.templates = window.templates || {}
  5.  
  6. // Store a DOM fragment of the template at window.templates[name]
  7. function readTemplateFromTag(tag) {
  8. return loadTemplate(tag.dataset.templateName, tag.textContent)
  9. }
  10.  
  11. // Load a template from a string
  12. function loadTemplate(name, content) {
  13.  
  14. window.templates[name] = document.createDocumentFragment()
  15.  
  16. Array.prototype.slice.call(
  17. new DOMParser()
  18. .parseFromString(content, 'text/html')
  19. .body
  20. .children
  21. ).forEach(function(child) {
  22. return window.templates[name].appendChild(child)
  23. })
  24.  
  25. }
  26.  
  27. // Populate a tag with the children of window.templates[name]
  28. function mountTemplate(string, tag, preflight, postflight) {
  29.  
  30. var template = document.querySelector(
  31. 'script[type="text/html"][data-template-name="'
  32. + string
  33. + '"]'
  34. )
  35.  
  36. readTemplateFromTag(template)
  37.  
  38. if (preflight) {
  39. preflight(window.templates[string])
  40. }
  41.  
  42. Array.prototype.slice.call(window.templates[string].childNodes)
  43. .forEach(function(child) {
  44. if (
  45. // tag is <style> or <script>
  46. (
  47. child.tagName.toLowerCase() === 'script'
  48. || child.tagName.toLowerCase() === 'style'
  49. )
  50. && (
  51. (
  52. // tag has textContent, and is already present in the document
  53. (
  54. child.textContent !== ''
  55. && Array.prototype.slice.call(document.getElementsByTagName(child.tagName.toLowerCase())).some(function(node) {
  56. return node.textContent === child.textContent
  57. })
  58. )
  59. // tag has src="", and is already present in the document
  60. || (
  61. child.src !== undefined
  62. && document.querySelector(child.tagName + '[src="' + child.src + '"]')
  63. )
  64. )
  65. )
  66. ) {
  67. false
  68. } else {
  69. tag.appendChild(child.cloneNode(true))
  70. }
  71. })
  72.  
  73. if (postflight) {
  74. postflight(tag)
  75. }
  76.  
  77. }
  78.  
  79. // Automatically mount named templates
  80. // usage: Populate matching template into any tag with data-template attribute
  81. // example: <custom-element data-template="demo">
  82. function autoMount() {
  83. return Array.prototype.slice.call(document.querySelectorAll('[data-template]'))
  84. .forEach(function(tag) {
  85. return mountTemplate(tag.dataset.template, tag)
  86. })
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement