如何从 CDN 动态加载 polyfil,而不是将它们捆绑到我的代码库中?

问题描述 投票:0回答:1

我需要加载我的应用程序的polyfill,才能在旧版浏览器上运行。我不想将 polyfill 捆绑到我的应用程序中,而是从我的入口文件内的 cdn 下载它们,并等待它们加载,然后再继续其余代码。

官方文档建议安装为依赖项,并在我的应用程序 src 代码之前添加 polyfill 脚本标记。

<!-- <script src="node_modules/@webcomponents/webcomponentsjs/webcomponents-loader.js"></script> -->

如何动态加载该加载后仅继续执行?

我使用 rollup 和 babel 进行捆绑,并且 polyfill 是特定于 Web 组件的:

https://github.com/webcomponents/polyfills/tree/master/packages/webcomponentsjs#how-to-use

此外,我的应用程序是一个网络插件,也将通过 CDN 的脚本标签加载。

web-component rollup polyfills
1个回答
0
投票

它就在您链接的页面上。

polyfill 有一个适合您情况的异步加载器模块

这是该页面的代码示例:

<!-- Load polyfills; note that "loader" will load these async -->
<script
  src="node_modules/@webcomponents/webcomponentsjs/webcomponents-loader.js"
  defer
></script>

<!-- Load a custom element definitions in `waitFor` and return a promise -->
<script type="module">
  WebComponents.waitFor(() => {
    // At this point we are guaranteed that all required polyfills have
    // loaded, and can use web components API's.
    // The standard pattern is to load element definitions that call
    // `customElements.define` here.
    // Note: returning the import's promise causes the custom elements
    // polyfill to wait until all definitions are loaded and then upgrade
    // the document in one batch, for better performance.
    return import('my-element.js');
  });
</script>

<!-- Use the custom element -->
<my-element></my-element>

不要将回调中的动态导入仅应用于

my-element.js
,这将是您导入组件入口点的位置。

© www.soinside.com 2019 - 2024. All rights reserved.