简体   繁体   English

动态加载Web组件/ HTML导入?

[英]Dynamically load Web Components / HTML Imports?

How would you go about dynamically loading a web component - in response to a url route change for example? 您将如何动态加载Web组件 - 例如,响应URL路由更改?

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? 我不会提前知道所请求的组件,所以你可以简单地使用JavaScript来编写HTML导入,然后将代码添加到页面中,或者是否有这样的含义? Perhaps Google Polymer helps? Google Polymer可能有帮助吗?

Considering just Custom Elements, you can call document.registerElement whenever you want. 只考虑自定义元素,您可以随时调用document.registerElement 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: 现在,关于HTML Imports:

could you simply use JavaScript to write the HTML import and then add the code to the page 你可以简单地使用JavaScript来编写HTML导入,然后将代码添加到页面中

Yes, that's the basic idea. 是的,这是基本的想法。

Recent versions of the HTML Imports polyfill support dynamic link tags. 最近版本的HTML Imports polyfill支持动态链接标记。 IOW, you can do IOW,你可以做到

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增强了对此功能的支持,即这样的命令式api:

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. 第一个参数是一个数组,因此您可以要求多个href。

Hi I asked this question over at the polymer google groups. 嗨,我在聚合物谷歌团体问了这个问题。 https://groups.google.com/forum/#!topic/polymer-dev/uarVrxBK7XU https://groups.google.com/forum/#!topic/polymer-dev/uarVrxBK7XU

and was directed to this article 并被引导到这篇文章

http://www.html5rocks.com/en/tutorials/webcomponents/customelements/#instantiating 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. 这清楚地表明,您可以通过将元素添加到dom或以编程方式实例化实例化元素。 However this appears to imply that you've loaded the html imports at runtime. 但是,这似乎意味着您已经在运行时加载了html导入。 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. 我认为我们都希望实现的是使用ajax加载html导入(使用额外的css和js包含)然后添加我们的元素。 I'm going to link back to the polymer support forum to see if I can get an answer over here. 我将链接回聚合物支持论坛,看看我能否在这里得到答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM