Javascript 在页面就绪之前动态加载WebComponents Polyfill
我正在开发一个小部件库,这样客户只需在文档的Javascript 在页面就绪之前动态加载WebComponents Polyfill,javascript,html,polymer,web-component,custom-element,Javascript,Html,Polymer,Web Component,Custom Element,我正在开发一个小部件库,这样客户只需在文档的中导入一个javascript文件。加载该文件后,用户应该能够使用从头部加载的单个脚本加载的自定义元素。 问题是我需要使用WebComponents polyfill,因为并非所有客户端都使用支持自定义元素的浏览器。 我目前的“解决方案”(不一致)是我有自己的捆绑包: 通过插入脚本将WebComponents捆绑包加载到中,动态包含WebComponents捆绑包。 我想使用WebComponents加载器,它将进行额外调用,以仅获取所需的多边形填充
中导入一个javascript文件。加载该文件后,用户应该能够使用从头部加载的单个脚本加载的自定义元素。问题是我需要使用WebComponents polyfill,因为并非所有客户端都使用支持自定义元素的浏览器。
我目前的“解决方案”(不一致)是我有自己的捆绑包:
中,动态包含WebComponents捆绑包。
- 我想使用WebComponents加载器,它将进行额外调用,以仅获取所需的多边形填充李>
//bundle-test.js
让polyfillScript=document.createElement('script');
polyfillScript.src='widget/webcomponentsjs/webcomponents bundle.js';
polyfillScript.async=false;
document.head.appendChild(polyfillScript);
…
你好,世界!
在定义自定义元素之前,您可以等待polyfill加载:
//bundle-test.js
let polyfillScript = document.createElement('script');
polyfillScript.src = '/webcomponentsjs/webcomponents-bundle.js';
polyfillScript.async = false;
document.head.appendChild(polyfillScript);
polyfillScript.onload = () =>
customElements.define( 'document-viewer', class extends HTMLElement {
connectedCallback() {
this.innerHTML = this.getAttribute( 'test' )
}
} )
另外,如果您想使用webcomponents loader.js,还必须使用webcomponents.waitFor
:
...
polyfillScript.onload = () =>
WebComponents.waitFor( () =>
customElements.define( 'document-viewer', class extends HTMLElement {
connectedCallback() {
this.innerHTML = this.getAttribute( 'test' )
}
} )
)
那很有帮助。但是,如果我在加载文档后定义自定义元素,浏览器是否知道返回这些元素并将其重新呈现为相应的自定义元素?@Andrew yes会的。