If you prefer to separate your ajax response template and only render it after receiving the response.
Alternatively, if you wish to keep everything in one template and append it to the page just once, Handlebars does not have native support for this as it focuses on creating logic-less templates and working with strings rather than DOM elements. You can achieve this by using a helper with Handlebars, or explore other popular templating solutions that might better suit your needs, such as searching for data binding templates.
If Handlebars is your preferred option, I have developed a custom helper that could be of use to you. Check out post-render-bars and its renderer helper. Take a look at this demo to see how it renders an ajax response.
The helper makes use of the MutationObserver, refer to this browser support information, and consider using webcomponents-lite for a polyfill if necessary.
A quick overview of the relevant code snippets:
watch.js introduces a function forHtml(html, callback)
that triggers a callback when the specified html is found in the DOM, temporarily assigning a unique class to the html.
helpers.js defines the helper renderer
and the function createRenderer(getHtmlContentFn)
which encapsulates your function into a renderer ready to be passed into a template as an argument for the helper.
The helper utilizes the watch.forHtml
function to monitor the block defined by the helper and connects it with the renderer. Each time the renderer function is executed, the relevant DOM element is updated accordingly.
Here's a condensed version of the provided example, starting with the template:
<p>Below is the Ajax response:</p>
{{#renderer response}}<div>Loading...</div>{{/renderer}}
Followed by the JavaScript code:
var context = {
response: postHandlebars.createRenderer(function(data) {
return data;
});
};
var html = template(context);
// append the html somewhere to visualize the response
$.ajax({
type: 'GET',
url: 'some url'
}).done(context.response);