Dynamically load Web Components / HTML Imports?

后端 未结 2 471
野趣味
野趣味 2020-12-16 19:12

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 c

2条回答
  •  -上瘾入骨i
    2020-12-16 19:37

    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.

提交回复
热议问题