Reputation: 2466
I need to append HTML dynamically into my web app. I'm not sure the best resource effective way of doing it. Instead of manually append each time like:
$('body).append('<div>[content here]</div>');
I created a module as a template:
var settings = (function(){
var commonTemplate = '<body id="ckit">'
+'<div class="ckit-container">'
[code removed for brevity]
+'</div>'
+'</body>';
return {
templates: {
toolbar : '<div id="ckit" class="layout-compact is-hiddenx" data-ckit-compact style="">'
[code removed for brevity]
+'<div id="ckit" class="layout-full is-hidden disable-scrolling" data-ckit-full>'+commonTemplate+'</div>',
loadingHtml: '<div class="ckit-preloader" data-loading>'
[code removed for brevity]
+'</div>',
createMessageForm: '<form action="" class="" data-create-message>'
[code removed for brevity]
+'</form>',
errorTemplate: '<div data-show-wrapper class="ckit-composer-files-wrapper">'
[code removed for brevity]
+'</div>',
},
};
})();
SO if I want HTML for to display error, I'll call system.errorTemplate();
And if I want to replace some value from server, I would:
for (var i = 0; i < data.length; i++) {
var clonedHtml = $(system.errorTemplate).clone();
clonedHttml.find('[data-find-this]').html('replace with this);
}
Is it effective way of appending html into DOM dynamically? Is there any other better way?
Upvotes: 0
Views: 35
Reputation: 16495
The way you are trying this looks good. In terms of performance there are some questions you could ask yourself to optimize.
If the content keeps static, means that the same dom gets appended over and over again, It would be better to create Document Fragments which you can clone()
and append, this way the parsing has to be done only once.
Another way would be to use the new hmtl5 <template>
link element, this way the browser will create DOM objects for you which are parsed a loading time.
To render dynamic data, the approaches are similar, the less string parsing happens, the faster it will be, however additionally to clone()
, you need some code inject the content into the new nodes.
Last but not least, there are also Frameworks like Handlebars or Moustache, which first compile each template to function, which expect a data object to render.
The more is computed in ahead, the faster it will be, but this might require some more code, than a simple search and replace.
Finally, rule of thumb: Modify dom element »offline«, and than append them to the DOM, Document Fragments can really help you doing that.
Upvotes: 1