Load HTML template with JavaScript

80,852

Solution 1

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/

$( "#result" ).load( "ajax/test.html" );

Solution 2

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

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

Solution 3

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.

Solution 4

another way to do this is using requireJS.

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

Solution 5

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();  
Share:
80,852
iancrowther
Author by

iancrowther

Updated on July 14, 2022

Comments

  • iancrowther
    iancrowther almost 2 years

    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.

  • iancrowther
    iancrowther almost 12 years
    Hi Andrei, Thanks for the answer, I have not really used requirejs but was aware of it, now I have a reason to tinker.. bennadel.com/blog/…
  • Andrei-Niculae Petre
    Andrei-Niculae Petre almost 12 years
    you can dynamically load a lot of stuff with it, it's very usefull. I use it for coffeescript code and templates.
  • Alexx Roche
    Alexx Roche almost 10 years
    Some example code is always nice. That's why I prefer peterp's answer
  • epergo
    epergo almost 9 years
    This was the solution for me, just don't forget to add the callback function! because if you are going to add functionality maybe the content is not loaded yet, so better to wait for it. $('#content').load('/templates.html', function () { // Things to do when the html is loaded });
  • Patrick Pirzer
    Patrick Pirzer over 7 years
    Is it possible to connect that template "template01.html" to a controller (defined in controller.js (Ionic/Cordova app)) without a state?
  • claudiadast
    claudiadast about 5 years
    I'm trying to incorporate this method in my Flask app but the html file does not load. I'd really appreciate any input! stackoverflow.com/questions/55735664/…
  • kleinohad
    kleinohad over 4 years
    @Felipe the answer is from 2011 you you can use it or not but you don't need to downvote
  • Felipe
    Felipe over 4 years
    @kleinohad jQuery has been replaced by native functions, which makes the answer outdated. IMO it should no longer be the accepted answer for a question that says "load HTML template with JavaScript"