javascript - HTML 模板和 HTML 导入 - Firefox 中不执行内部脚本

标签 javascript html firefox web-component html5-template

我正在使用 webcomponents.js 来填充 Firefox 对网络组件的支持。

通过 HTML 导入加载 HTML 模板时,一旦将基于模板的自定义元素添加到主页的 DOM 中,模板中的脚本就不会执行。

它确实在 Chrome 中运行网站时执行(它具有 native Web 组件支持)。

但是,当模板放在主页本身时,Firefox 和 Chrome 都会执行这样的脚本。

请参阅 Eric Bidelmann 的示例,网址为 HTML5Rocks .这可以在 Chrome 和 Firefox 中运行(通过 webcomponents.js)——只要模板位于同一个 HTML 文件中。

<!DOCTYPE html>
<html>
<body>

<button onclick="useIt()">Use me</button>
<div id="container"></div>
<script>
  function useIt() {
    var content = document.querySelector('template').content;
    // Update something in the template DOM.
    var span = content.querySelector('span');
    span.textContent = parseInt(span.textContent) + 1;
    document.querySelector('#container').appendChild(
        document.importNode(content, true));
  }
</script>

<template>
  <div>Template used: <span>0</span></div>
  <script>alert('Thanks!')</script>
</template>



</body>
</html>

但是当模板文本显示时,它不会在通过 HTML 导入链接加载模板及其内容时运行。如前所述,它会加载内容,但不会在 Firefox 中执行脚本。

这是 webcomponents.js 中的错误,还是 Firefox 中的错误? 有人对解决方法(“使用 Polymer 或 Angular”除外)有好的想法吗?

注意 - 这是基于使用 Firefox 43 和 Chrome 47。

最佳答案

这不是 Firefox 中的错误,Internet Explorer 11 具有相同的行为(使用 webcomponents.js)。

importNode方法未由 webcomponents.js 填充。这就是为什么 <script>元素在导入时未激活。

有一个issue opened与那个问题有关。

我的解决方法:我不插入脚本标签 <script>在进口 <template> 内(JS/HTML 分离:)。

另外,你可以解析你的 <template>正在寻找 <script>标签并尝试手动激活/执行它们(可能有点棘手......)

关于javascript - HTML 模板和 HTML 导入 - Firefox 中不执行内部脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35047590/

相关文章:

javascript - jquery 中的异步 foreach

python - 使用 Selenium 启动的 Firefox 与系统默认的 Firefox 设置不同

firefox - Firefox 中不显示 Google Adsense 广告

javascript - 在 Javascript 中解构对象 - ngbind - Angular 4+

javascript - 在坐标数组中找到最接近给定的点

javascript - 将鼠标悬停在第二列上时更改表中第一列的 CSS 样式

javascript - Safari iOS 不加载 Javascript 文件?

javascript - 如何实现类似于 youtube 卡片的上下文菜单?

javascript - 在 Firefox 中使用 JavaScript 在 iframe 中打印 PDF

javascript - 如何删除传单上按类型分类的特定标记?