javascript - 尝试在 html 导入中选择模板元素时获取 null

标签 javascript html templates web-component html5-template

在我的应用程序中,我将 A 的 html 导入到包含此文件的 B 中。但它警告为空。如果我直接在浏览器中打开 B,它会提醒模板 HTML dom 元素。这怎么可能发生,同样的代码几乎来自谷歌自己的网络组件文档https://developers.google.com/web/fundamentals/architecture/building-components/customelements .

<template id="x-foo-from-template">

</template>

<script>
    alert(document.querySelector('template'));
</script>

这是谷歌的例子:

<template id="x-foo-from-template">
  <style>
    p { color: orange; }
  </style>
  <p>I'm in Shadow DOM. My markup was stamped from a &lt;template&gt;.</p>
</template>

<script>
  customElements.define('x-foo-from-template', class extends HTMLElement {
    constructor() {
      super(); // always call super() first in the ctor.
      let shadowRoot = this.attachShadow({mode: 'open'});
      const t = document.querySelector('#x-foo-from-template');
      const instance = t.content.cloneNode(true);
      shadowRoot.appendChild(instance);
    }
    ...
  });
</script>

谢谢

最佳答案

为什么会这样?

导入包含脚本模板的文件时要考虑的两个因素:

  1. 脚本 将在导入时执行,而标记和其他资源需要显式添加到主页
    • 正如本 article on imports 中所指出的(Eric Bidelman,与相关 Google 文档的作者相同):

An import link doesn't mean "#include the content here". It means "parser, go off an fetch this document so I can use it later". While scripts execute at import time, stylesheets, markup, and other resources need to be added to the main page explicitly.

  1. 导入中的脚本在包含导入文档的窗口的上下文中执行。所以window.document指的是主页面文档,不是模板文档。

这应该可以解释为什么您的脚本会提示 null。因为脚本是立即执行的,而模板还没有添加到主页面。

如何得到想要的结果:

您可以在可以找到模板的地方创建对导入文档本身的引用。

// importDoc references this import's document
var importDoc = document.currentScript.ownerDocument;

alert(importDoc.querySelector('template'));

或者,您可以在将模板插入文档后查询主文档:

var import = document.querySelector('link[rel="import"]').import;
var template = import.querySelector('template');

// Append template to main document
document.head.appendChild(template);

// Now you can query the main the document
alert(document.querySelector('template'));

Google 的示例与所讨论的示例有何不同?

在回答下面评论中的问题时:

在 Google 的示例中,可以在自定义元素的构造函数中找到对 document.querySelector() 的调用。实例化元素时调用构造函数。因此,运行此代码时该元素已存在于主页面中。

关于javascript - 尝试在 html 导入中选择模板元素时获取 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45726483/

相关文章:

javascript - 每5分钟移动一次鼠标的脚本

javascript - 使用 javascript 从 JSON 文件搜索并从本地存储加载

媒体查询中文本下方的 CSS 按钮位置

javascript - 单击提交后如何从当前事件的轮播中获取所有输入值?

c++ - 自定义对象的常量表达式

c++11 - has_iterator 如何在给定代码中工作?

javascript - 如何高效地将大文件加载到 IndexedDB 存储中?我的应用程序在超过 100,000 行时崩溃

html - Bootstrap 响应式网格获取一列

c++ - 是否可以为模板化类型专门化模板?

javascript - Vue.js:重新定义图表数据