动态加载Web组件/ HTML导入? [英] Dynamically load Web Components / HTML Imports?

查看:413
本文介绍了动态加载Web组件/ HTML导入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何动态加载网络组件 - 例如,为了响应网址路由更改?

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

我不会提前知道所请求的组件,那么你可以简单地使用JavaScript来编写HTML导入,然后将代码添加到页面中,或者是否有这样的含义?也许谷歌聚合物有帮助?

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?

推荐答案

只考虑自定义元素,你可以调用 document.registerElement 随时随地。因此,从这个角度来看,您可以使用任何众所周知的方法动态加载脚本并拥有动态自定义元素。

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.

现在,关于HTML Imports:

Now, with respect to HTML Imports:


您可以简单地使用JavaScript编写HTML导入,然后将
代码添加到页面

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

是的,这是基本想法。

最近版本的HTML Imports polyfill支持动态链接标记。 IOW,你可以做到

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);

此外,Polymer增强了对此功能的支持,即这样的命令式api:

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
});

第一个参数是一个数组,所以你可以要求多个hrefs。

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

这篇关于动态加载Web组件/ HTML导入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆