Dynamically load web components / HTML import?

How would you dynamically load a web component - for example, in response to a URL route change?

I will not know the requested component ahead of time, so that you could just use JavaScript to write the HTML import, and then add the code to the page, or are there any consequences with this? Perhaps Google Polymer helps?

+7
javascript html5 polymer web-component
source share
2 answers

Given only user elements, you can call document.registerElement whenever you want. From this point of view, you can dynamically load the script using any known method and have dynamic user elements.

Now, regarding the import of HTML:

You could just use JavaScript to write the HTML import, and then add the code to the page

Yes, that’s the main idea.

Recent versions of HTML Imports polyfill support dynamic link tags. IOW you can do

 var link = document.createElement('link'); link.setAttribute('rel', 'import'); link.setAttribute('href', some_href); link.onload = function() { // do stuff with import content }; document.body.appendChild(link); 

In addition, Polymer has improved support for this function, namely the imperative api, like this:

 Polymer.import([some_href], function() { // called back when some_href is completely loaded, including // external CSS from templates }); 

The first argument is an array, so you can request multiple hrefs.

+12
source share

Hi, I asked this question in Google Groups. https://groups.google.com/forum/#!topic/polymer-dev/uarVrxBK7XU

and was sent to this article

http://www.html5rocks.com/en/tutorials/webcomponents/customelements/#instantiating

This makes it clear that you can create an element on the fly by adding the element to dom or programmatically. However, this means that you loaded the html import at runtime. What I think we both want to achieve is loading the html import (with the addition of additional css and js) using ajax and then adding our element. I will return to the polymer support forum to find out if I can get an answer here.

+4
source share

All Articles