Polymer tips: Don’t pollute your DOM with dialogs

We aim to avoid unnecessary DOM nodes as they slow down web applications.

Most examples for Polymer’s paper-dialog stamp the node at creation and keep it in the DOM forever. Keeping dozens of unused paper-dialog nodes in the DOM becomes quickly an issue in larger applications.

We therefore add the dialog to the DOM on opening and remove it again on closing:

open: function() {
Polymer.dom(document.body).appendChild(this);
this.$.dialog.open();
},
close: function() {
this.$.dialog.close();
Polymer.dom(this.parentNode).removeChild(this);
}

We attach the dialog to the document body to ensure that the dialog is on top of all existing overlays.

There is one more catch: The dialog might not open in mobile Safari because the node isn’t available when calling open(). To counter that, we wait for a millisecond to ensure the dialog is there:

open: function() {
Polymer.dom(document.body).appendChild(this);
  setTimeout(function() {
this.$.dialog.open();
}.bind(this), 1);

}

See paper-alert-dialog for a full example.

Happy coding!

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