我正在尝试使用webcomponents.js
填充物使用自定义 Web 组件。我一直在使用 https://github.com/webcomponents/hello-world-element 的<hello-world>
元素
Safari和Firefox不会显示任何内容,并给我以下错误:
野生动物园:TypeError: null is not an object (evaluating 'thisDoc.querySelector('template').content')
火狐:TypeError: thisDoc.querySelector(...) is null
问题出在哪里:
我修改了hello-world.html
.它现在记录模板查询选择器的结果:
// Gets content from <template>
console.log('thisDoc.querySelector("template")', thisDoc.querySelector('template'));
var template = thisDoc.querySelector('template').content;
控制台输出给了我null
.这可能就是代码的其余部分无法正常工作的原因。有什么想法吗?
我的系统:
Safari: Version 8.0 (10600.1.25.1)
Firefox: 31.0
OS: OS X Yosemite 10.10.1 (14B25)
我还在github上发布了一个问题:https://github.com/webcomponents/hello-world-element/issues/7#issuecomment-65321859
有没有人知道让 polyfill 在 Safari/Firefox 中工作的解决方案?谢谢!
我找到了这个问题的解决方案。您现在可以将 Web 组件与 Chrome 上的原生 API 以及 Firefox 和 Safari 上的 polyfill 一起使用。
只需更新此行:
var thisDoc = (thatDoc.currentScript || thatDoc._currentScript).ownerDocument;
自
var thisDoc = (thatDoc._currentScript || thatDoc.currentScript).ownerDocument;
为什么会这样?
_currentScript来自 polyfill,并允许您获取正确的所有者文档以从中查询<template>
。如果 polyfill 不存在,则上面的代码改用 currentScript,这在 Chrome 上可用。
我已经在github上发出了拉取请求。