Home » Html » Load HTML template with JavaScript

Load HTML template with JavaScript

Posted by: admin November 30, 2017 Leave a comment

Questions:

I am struggling to find a clean solution to my problem and was wondering if anyone could offer some tips.

I have “templates.html” which contains a collection of HTML snippets which I want to load into JavaScript and use. What is a good way to access the templates/snippets bearing in mind that templates.html is not a loaded DOM document?

I was thinking about using document.open to create a DOM to access but I think this has issues on certain browsers.

Answers:

You can load the html into a hidden div and then you will have a DOM access
the easiest way to load the html to a DIV is using jquery load: http://api.jquery.com/load/

Questions:
Answers:

Use jQuery and the .load() ( http://api.jquery.com/load/
) method to inject the loaded document into the DOM.

$(function() {
    $('#content').load('/templates.html');
});

Questions:
Answers:

another way to do this is using requireJS.

require (['text!template_name'], function(yourTemplate) {
  // do stuff in here with yourTemplate dinamically load
}

Questions:
Answers:

For simple requiring you can try:

var xhr = new XMLHttpRequest(); 
xhr.onreadystatechange = function () {
    if (xhr.readyState === 4) {     
        //do something with xhr.responseText
    }   
};      
xhr.open('GET', '/template.html');
xhr.send();  

Questions:
Answers:

you could load the template async using jquery ajax

$.get("/html/template01.html")
.done((data) => {
    console.info(data); // output the content of the html file
});

Questions:
Answers:

This is a bit old but since “Load HTML template with JavaScript” nowadays should refer to the loading of a HTMLTemplateElement here is a more modern looking approach to loading natives templates with javascript that also works for your use case.

First of all using <template> is already better than loading HTML into a hidden DIV because templates are innert and don’t display content. You can have the templates being rendered from the beginning and use them whenever you need.

<html>
<head>
  <template>My template</template>
</head>
<body>
  <script>
  document.body.append(
    document.importNode(
      document.querySelector('template').content,
      true
    )
  )
  </script>
</body>
</html>

Or create them dynamically.

const template = document.createElement('template')
// modify the template's content
template.content.append(document.createElement('div'))
// add it to the document so it is parsed and ready to be used
document.head.append(template)

Because we want the content of the template to be built based on some text we get from the network, we have to parse it and add it to our template.content.

const text = fetchTemplateSomehowAsText('my-template.html')
const parsedDocument = new DOMParser().parseFromString(text, 'text/html')
template.content.append(parsedDocument.querySelector('#my-snippet'))

If my-template.html already comes wrapped in the <template> tag we can avoid the part of creating the template element manually because the DOMParser already creates the template element for us.

document.head.append(
  new DOMParser().parseFromString(text, 'text/html')
    .querySelector('template')
  )
)

This is a snippet I’ve been using to load templates into the document dynamically that uses what I just explained.