Load HTML template with JavaScript

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/


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

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

actually, the best way to do this is using requireJS.

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

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();  

Need Your Help

How to link VBA app against debug mode COM DLL

visual-studio vba excel-vba excel-2007

I am trying to debug an VBA excel app that invokes some functions from a C++ COM DLL.

How to record user's voice from the website but without Flash?

php javascript web-services html5

How to record user's voice from the website without Flash? I want to use HTML5 but I found it will be hard to implement that. This site says this functionality is now only supported by the latest v...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.