Dynamically load Web Components / HTML Imports?
Asked Answered
A

2

11

How would you go about dynamically loading a web component - in response to a url route change for example?

I won't know the requested component ahead of time, so could you simply use JavaScript to write the HTML import and then add the code to the page, or are there implications with this? Perhaps Google Polymer helps?

Antonioantonius answered 6/2, 2014 at 15:53 Comment(0)
G
12

Considering just Custom Elements, you can call document.registerElement whenever you want. So from that standpoint, you can dynamically load script using any well known method and have dynamic custom elements.

Now, with respect to HTML Imports:

could you simply use JavaScript to write the HTML import and then add the code to the page

Yes, that's the basic idea.

Recent versions of the 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);

Also, Polymer has enhanced support for this feature, namely an 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 ask for multiple hrefs.

Guacin answered 8/2, 2014 at 17:20 Comment(1)
If you are building a chrome extension/app you will need to use the former and not the latter due to this issue: github.com/Polymer/polymer/issues/810Bratcher
T
3

Hi I asked this question over at the polymer google groups. https://groups.google.com/forum/#!topic/polymer-dev/uarVrxBK7XU

and was directed to this article

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

This makes it clear you can instantiate an element on the fly by either adding the element to the dom or programatically. However this appears to imply that you've loaded the html imports at runtime. What I think we both want to achieve is loading the html imports (with additional css and js includes) using ajax and then add our element. I'm going to link back to the polymer support forum to see if I can get an answer over here.

Tangy answered 7/2, 2014 at 12:22 Comment(1)
Sorry to reanimate this one: But did you got any further with this?Mainstream

© 2022 - 2024 — McMap. All rights reserved.