Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
244 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...