Polymer tips: Avoid unnecessary DOM nodes

Ronny Roeller
NEXT Engineering
Published in
1 min readDec 19, 2015

Unnecessary DOM nodes slow down web applications. Hence, we should avoid such waste whenever possible.

I frequently spot this anti-pattern in our Polymer elements:

<dom-module id="my-element">
<template>
<div>
<span>Element 1</span>
<span>Element 2</span>
</div>
</template>
</dom-module>

The div basically acts as a holder for the elements in the template. This div holder can be easily avoided by styling the host element itself:

<dom-module id="my-element">
<style>
:host {
display: block;
}

</style>
<template>
<span>Element 1</span>
<span>Element 2</span>
</template>
</dom-module>

A complication might arise if you need to set an attribute on the holder for styling, e.g.:

<dom-module id="my-element">
<style>
#holder[has-error] .text {
color: red;
}

</style>
<template>
<div id="holder" has-error="[[hasError]]">
<span class="text">[[text]]</span>
...

But Polymer has also a neat solution for such situations! Just reflect the property on the host itself with reflectToAttribute:

<dom-module id="my-element">
<style>
:host[has-error] .text {
color: red;
}

</style>
<template>
<span class="text">[[text]]</span>
</template>
...
<script>(function() {
Polymer({
is: "my-element",
properties: {
hasError: {
type: Boolean,
reflectToAttribute: true
},
...

Happy coding!

Want to learn more about Polymer? Have a look to all our Medium posts on Polymer.

--

--

Ronny Roeller
NEXT Engineering

CTO at nextapp.co # Product discovery platform for high performing teams that bring their customers into every decision