Polymer is a web components library and can be used to create custom elements. The library works on all major browsers (using polyfills) even if a browser does not support web components.
Install polymer
Assuming you have bower installed, run the following to create a project with polymer dependencies.
$ cd my_polymer_project $ bower init ## pick any project name, etc. or keep defaults $ bower install polymer --save
Note that the following directories will be created.
bower_components/webcomponentsjs/
bower_components/polymer/
Create custom element using polymer
Create am html file (say index.html) with the following code. You may have to change the path of bower_components
depending upon how you run the main index.html file.
<script src="/lib/polymer-1.3.0/bower_components/webcomponentsjs/webcomponents-lite.min.js"></script> <link rel="import" href="/lib/polymer-1.3.0/bower_components/polymer/polymer.html"> <h2>Polymer custom element outcome</h2> <my-element></my-element> <script> window.addEventListener('WebComponentsReady', function() { Polymer({ is: "my-element", ready: function() { this.innerHTML = "<p>Hello world from Polymer</p>"; } }); }); </script>
Few points to note
-
We need to wait for
WebComponentsReady
event before we define out custom element. This is to ensure that all web components are ready before we use them. - The element name must have a dash in it.
-
We could have put the custom code in a separate element html (say my-element.html) and imported it from main file (say index.html). Here is how my-element.html will look like with that approach:
<link rel="import" href="/lib/polymer-1.3.0/bower_components/polymer/polymer.html"> <script> Polymer({ is: "my-element", ready: function() { this.innerHTML = "<p>Hello world from Polymer</p>"; } }); </script>
And here is the main index.html file and its rendered outcome.
<script src="/lib/polymer-1.3.0/bower_components/webcomponentsjs/webcomponents-lite.min.js"></script> <link rel="import" href="/lib/polymer-1.3.0/bower_components/polymer/polymer.html"> <link rel="import" href="/demo2/polymer/my-element.html"> <h2>Polymer custom element outcome</h2> <my-element></my-element>