检测聚合物的浏览器支持

And*_*dre 9 cross-browser polymer

我在网站上使用Polymer(版本0.5,可能在某些时候升级到1.0).很明显,许多旧版浏览器与Polyfill不兼容.

有没有办法测试polyfill在特定浏览器中是否成功?因此,在完成polyfill之后,是否有一些函数,对象,变量或任何我可以检查以查看polyfill是否有效的东西?

我希望能够检测到故障,然后重定向到带有"请升级"消息的页面.

对我来说唯一的选择是在我的后端实现某种浏览器检测中间件,由于各种内部原因,我宁愿在此时避免这种中间件(并且因为它意味着特定的白名单/黑名单列表的浏览器,这将成为繁琐快速).

Thx提前.

Odd*_*Dev 4

简短回答:

\n\n

快速测试:Firefox 38.0.5 提示“否”,而 Chrome 44.0.2403.130 m 提示“是”

\n\n

\r\n
\r\n
function supportsPolymer() {\r\n  return \'content\' in document.createElement(\'template\') && \'import\' in document.createElement(\'link\') && \'registerElement\' in document && document.head.createShadowRoot;\r\n}\r\n\r\nif(supportsPolymer()) {\r\n  \r\n  //Good to go\r\n  alert("Yes");\r\n  \r\n} else {\r\n  \r\n  //Is not supported\r\n  alert("No");\r\n  \r\n}
Run Code Online (Sandbox Code Playgroud)\r\n
\r\n
\r\n

\n\n

详细解答:

\n\n

您必须在 Polymer 的网站上查看此列表。

\n\n
\n
    \n
  • 模板
  • \n
  • HTML 导入
  • \n
  • 自定义元素
  • \n
  • 影子 DOM
  • \n
\n
\n\n

必须支持这些功能:

\n\n\n\n
\n
function supportsTemplate() {\n  return \'content\' in document.createElement(\'template\');\n}\n\nif (supportsTemplate()) {\n  // Good to go!\n} else {\n  // Use old templating techniques or libraries.\n}\n
Run Code Online (Sandbox Code Playgroud)\n
\n\n
\n\n\n\n
\n
function supportsImports() {\n  return \'import\' in document.createElement(\'link\');\n}\n\nif (supportsImports()) {\n  // Good to go!\n} else {\n  // Use other libraries/require systems to load files.\n}\n
Run Code Online (Sandbox Code Playgroud)\n
\n\n
\n\n\n\n
\n
function supportsCustomElements() {\n  return \'registerElement\' in document;\n}\n\nif (supportsCustomElements()) {\n  // Good to go!\n} else {\n  // Use other libraries to create components.\n}\n
Run Code Online (Sandbox Code Playgroud)\n
\n\n
\n\n\n\n

如何检查浏览器是否支持 Shadow DOM

\n\n
\n
if(document.head.createShadowRoot) {\n    // I can shadow DOM\n} else {\n    // I can\'t\n}\n
Run Code Online (Sandbox Code Playgroud)\n
\n\n

在一个函数中:

\n\n
 function supportsShadowDom() {\n   return document.head.createShadowRoot;\n }\n
Run Code Online (Sandbox Code Playgroud)\n\n

未经测试的版本采用前面片段的风格:

\n\n
 function supportsShadowDom() {\n   return \'createShadowRoot\' in document;\n }\n
Run Code Online (Sandbox Code Playgroud)\n\n
\n\n

好的,在实现每个功能后,您可以执行以下操作:

\n\n
 if (supportsCustomElements() && supportsTemplate() && supportsImports() && supportsShadowDom()) {\n   // Good to go!\n } else {\n   // Use other libraries to create components.\n }\n
Run Code Online (Sandbox Code Playgroud)\n\n

这是来自https://github.com/WebComponents/webcomponentsjs#browser-support的当前矩阵:

\n\n

\r\n
\r\n
function supportsTemplate() {\n  return \'content\' in document.createElement(\'template\');\n}\n\nif (supportsTemplate()) {\n  // Good to go!\n} else {\n  // Use old templating techniques or libraries.\n}\n
Run Code Online (Sandbox Code Playgroud)\r\n
\r\n
\r\n

\n\n

这可能也很有趣:\n https://github.com/webcomponents/webcomponentsjs/issues/26

\n