Search code examples
polymerpolymer-1.0polymer-starter-kit

Polymer 1.0: Do <script> tags go inside or outside the <dom-module>?


Question

Which method of placing the <script> tags is "best-practice?"

  • Inside the <dom-module>?

or

  • Outside the <dom-module>?

Also, please answer:

  1. Why?
  2. What is the source of your answer?
  3. What downside risks are there by doing it the "wrong" way?

Polymer Starter Kit: OUTSIDE

In the Polymer Starter Kit, the my-list.html and my-greeting.html files place the <script> tag outside the <dom-module>.

Like this:

<dom-module>
  <style>...</style>
  <template>...</template>
<dom-module>
<script>...</script>

Other Experts: INSIDE

However, I have heard and seen several examples from Google employees and Google developers that suggest the <script> tags should go inside the <dom-module>.

Like this:

<dom-module>
  <style>...</style>
  <template>...</template>
  <script>...</script>
<dom-module>

Solution

  • The correct answer is - it shouldn't matter. While the documentation is indeed as @Mowzer noted, this is just an example rather than a definition. At least some actual Polymer elements like e. g. iron-image have it outside dom-module.

    The relationship between the dom-module and the object Polymer constructor defines is established through the 'is' property of the object passed to the Polymer constructor and the id attribute of the dom-module.

    From Local DOM guide:

    Give the <dom-module> an id attribute that matches its element’s is property and put a inside the <dom-module>. Polymer will automatically clone this template’s contents into the element’s local DOM.

    As a side note, you can also successfully use <script src="external.js"></script> to separate the html from the JS - I'm just guessing this is one possible reason for this question. The only drawback to this (AFAIK) is that in this case a vulcanized version of your element will show incorrect (offset) code line numbers for JS errors.