gpt4 book ai didi

javascript - 如何有条件地使用再生器运行时 polyfill?

转载 作者:行者123 更新时间:2023-11-28 04:53:12 26 4
gpt4 key购买 nike

This article启发我将我为 React 应用程序加载的 polyfill 外部化,并且只为需要它们的浏览器加载它们。一个简单的测试:

function browserSupportsAllFeatures() {
return window.Promise && window.fetch && window.regeneratorRuntime
}

然后将确定是否应加载填充:

if (browserSupportsAllFeatures()) {
// Browsers that support all features run `main()` immediately.
main()
} else {
// All other browsers loads polyfills and then run `main()`.
loadScript('/path/to/polyfills.js', main)
}

function main(err) {
// Initiate all other code paths.
// If there's an error loading the polyfills, handle that
// case gracefully and track that the error occurred.
}

但是,我在代码中使用了生成器,这似乎有点边缘情况。据我了解,babel 转换生成器( https://babeljs.io/docs/plugins/transform-regenerator/ ),并且转换后的代码还需要定义 regeneratorRuntime (使用 this package )。

所以我的应用程序失败,因为导入 App 时未定义 regeneratorRuntime (其中包含使用生成器的代码)。所以我的 polyfill 来得太晚了:

// import dependencies
import React from 'react'
import { render } from 'react-dom'
import { App } from './components/app'

const renderApp = () => {
render(<App />, document.getElementById('app'))
}

function browserSupportsAllFeatures() {
return window.Promise && window.fetch && window.regeneratorRuntime
}

if (browserSupportsAllFeatures()) {
renderApp()
} else {
loadScript('/path/to/polyfills.js', renderApp);
}

我知道我可以通过在顶部导入再生器来解决这个问题,但这里的目的是外部化polyfills并使它们有条件。

所以我的问题是;如何继续使用生成器,但仍将我的 polyfill 包含在 loadScript 调用中?

最佳答案

您可以使用以下方式检查属性:

if (window.hasOwnProperty("regeneratorRuntime")) ...

npm 包 polyfill-io-feature-detection 的作用完全相同,请查看此解决方案以了解它如何处理特征检测: https://github.com/jquintozamora/polyfill-io-feature-detection

关于javascript - 如何有条件地使用再生器运行时 polyfill?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42739695/

26 4 0
文章推荐: html - 如何使用 bootstrap 填充空白
文章推荐: jquery - 单击 显示/隐藏
文章推荐: html - margin 不透明
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com