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 - 如何比较依赖于语言环境的 float ?

javascript - OnClick 发送到 Ajax

javascript - 高分辨率图像加载时的图像闪烁

html - 如何让自动换行以更小的宽度换行

javascript - 如何在 react router dom 中将不存在的路由重定向到主页?

html - HTML5 中的视频流

html - 如何使 div 具有可变宽度以填充父级的其余部分并在必要时使自身可滚动

firefox - 添加 Cookie 关键字未按预期设置 cookie

java - 在路径中找不到 firefox 二进制文件

css - 使用字体变体 : small caps & text-transform: capitalize 时,Firefox 显示其中带有 x 的框