简体   繁体   中英

Polymer template and style tag relation

I know that Polymer recommends to use style tag inside template tag since v1.1 but supports both. Can anyone tell me the advantages of doing so. If it is inertness then can you please give an example where keeping style tag outside template exposed it outside of shadow-dom

The 1.1 release notes indicate performance reasons:

Previously, we recommended that a <style> element should be placed inside an element's <dom-module> but outside of its template. This is still supported, but we've now optimized placing styles within the template itself, so having the <style> tag outside of the template will be slower.

If I read the code correctly, this is Polymer's procedure for parsing CSS:

  1. Select child nodes that can contain CSS (including <style> and <template> ).
  2. For each node:

    a. If the node is <template> , recurse on the node (go to step 1).

    b. Else if the node is <style> , remove the node (to prevent style leak), and then append the node's text to the string buffer.

    c. Else if the node is <link rel="import" type="css"> , append its imported text to the string buffer.

  3. Return the string buffer.

If all styles are parsed using this procedure, I don't understand how the placement of <style> would affect performance (maybe I'm missing something).

please give an example where keeping style tag outside template exposed it outside of shadow-dom

The <style> doesn't leak regardless of whether it's placed inside the <template> (because of step 2b above), as seen in the following demos.

 <head> <base href="https://polygit.org/polymer+1.5.0/components/"> <script src="webcomponentsjs/webcomponents-lite.min.js"></script> <link rel="import" href="polymer/polymer.html"> </head> <body> <x-foo></x-foo> <div class="title">outside &lt;x-foo&gt; (should not be styled)</div> <dom-module id="x-foo"> <style> div.title { font-family: Arial; color: blue; } </style> <template> <div class="title">inside &lt;x-foo&gt;</div> </template> <script> HTMLImports.whenReady(function() { Polymer({ is: 'x-foo' }); }); </script> </dom-module> </body> 

codepen

 <head> <base href="https://polygit.org/polymer+1.5.0/components/"> <script src="webcomponentsjs/webcomponents-lite.min.js"></script> <link rel="import" href="polymer/polymer.html"> </head> <body> <x-foo></x-foo> <div class="title">outside &lt;x-foo&gt; (should not be styled)</div> <dom-module id="x-foo"> <template> <style> div.title { font-family: Arial; color: blue; } </style> <div class="title">inside &lt;x-foo&gt;</div> </template> <script> HTMLImports.whenReady(function() { Polymer({ is: 'x-foo' }); }); </script> </dom-module> </body> 

codepen

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM