Load HTML template with JavaScript
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();
iancrowther
Updated on July 14, 2022Comments
-
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 almost 12 yearsHi 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 almost 12 yearsyou can dynamically load a lot of stuff with it, it's very usefull. I use it for coffeescript code and templates.
-
Alexx Roche almost 10 yearsSome example code is always nice. That's why I prefer peterp's answer
-
epergo almost 9 yearsThis 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 over 7 yearsIs it possible to connect that template "template01.html" to a controller (defined in controller.js (Ionic/Cordova app)) without a state?
-
claudiadast about 5 yearsI'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 over 4 years@Felipe the answer is from 2011 you you can use it or not but you don't need to downvote
-
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"