Search code examples
namespacespolymerglobalencapsulationpolymer-1.0

Polymer components don't encapsulate javascript


I know that encapsulation of javascript is not part of the web component W3C spec but, what are some strategies for avoiding global namespace pollution with Polymer?

For example, if I include <script src="./jquery.js"></script> in my Polymer component then $ leaks into the the host page's window object. This is very problematic for me as I am using Polymer in a chrome extension.


Solution

  • One way might be to make a jquery-api.html like this:

    <script src="[path.to]jquery.js"></script>
    <script>
    (function() {
      // make local $
      var $ = window.$;
      // kill globals
      $.noConflict(true);
      // make $ available via custom-element registry
      Polymer({
        is: 'jquery-api',
        get $() {
         return $;
        }
      });
    })();
    </script>
    

    Then you could use it anywhere you need to like this:

    <link rel="import" href="jquery-api.html">
    <script>
    (function() {
      var $ = document.createElement('jquery-api').$;
      Polymer({
        is: 'jquery-user'
        /* can use $ in here */
      });
    })();
    </script>