Flooding DOM by using HTML templates

Photo by Irvan Smith on Unsplash

Some time back I’ve discovered and started to use an amazing feature of HTML 5: templates. If you never heard about it – you definitely should visit HTML 5 Rocks website to read about pros and cons of these functionality. But anyway this post is not about feature itself, but about some pitfall, which I’ve faced after some time.

So, let’s imagine, that you are going to write some page with a dynamic content, which will be generated by using some AJAX calls and templates mechanism. For example you are not satisfied with slow data-binding from existing frameworks (all of them are too generic) and you developed your own data-binding with blackjack and… anyway, you have some HTML:

So, now we want to bind some data to this template. So basically, what I will do – is just reuse this template 1000 times and then… drop all nodes, that I’ve been added this way (for example you need to remove everything, that outside the viewport):

And now the most interesting part. You, probably are expecting, that DOM is in the same state as it was before I’ve done these strange manipulations. But it’s not.

Clean DOM

Flooded DOM

What’s wrong? The answer is very simple. Let’s go into debugger and find an answer:
Text nodes

Yes, so every tab, newline and other character, that is not HTML tag – creates Text Node. I believe most of developers prefer to format their code with tabs and spaces, but sometimes it can lead to some unexpected behavior. So, it’s fine to use this pretty-printing on development boxes, but don’t forget to minimize your HTML before moving it to production:

In this example (you can easily check it in your browser) – you will not get any issues with memory leaks in DOM.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s