javascript - 浏览器如何处理 <template> 标签 VS <div> 标签

标签 javascript html html5-template

我一直在阅读有关 <template> 的文档标签,我似乎无法理解它与简单地使用 <div> 有何不同那是 display: none;

文档:template tag

<template>例子

<template id="productrow">
  <tr>
    <td class="record"></td>
    <td></td>
  </tr>
</template>

对比 <div>例子

<div id="productrow" style="display: none">
  <tr>
    <td class="record"></td>
    <td></td>
  </tr>
</div>
  1. 在底层,浏览器如何以不同方式处理这两个示例?
  2. 某些 JS 方法或 HTML 属性是否不同或不可用?

PS:我知道浏览器兼容性差异

最佳答案

考虑:

<template>
  <style>
    body: { background-color: black; }
  </style>
  <script>
    alert('hello');
  </script>
  <audio src="alert.wav" autoplay></audio>
</template>

和:

<div style="display: none;">
  <style>
    body: { background-color: black; }
  </style>
  <script>
    alert('hello');
  </script>
  <audio src="alert.wav" autoplay></audio>
</div>

当浏览器呈现它们时,它们的行为是否相同? (剧透:没有。)

不过,要解决您的具体问题:

  1. On a low level, how does the browser handle these 2 examples differently?

首先,<template> 中的 HTML不会成为 <template> 的子元素的 DOM 元素.它成为“惰性”DocumentFragment 的子项(间接地;这是一种简化),它们作为节点存在但不“做”任何事情,如上例所示。

除了“惰性”之外,模板内容没有“一致性要求”。你的<tr>上面的例子是一个很好的例子。看看这里发生了什么:

const template = document.querySelector('template');
const div = document.querySelector('div');

console.log('template.innerHTML is', template.innerHTML);
console.log('div.innerHTML is', div.innerHTML);
<template>
  <tr>
    <td class="record"></td>
    <td></td>
  </tr>
</template>

<div style="display: none">
  <tr>
    <td class="record"></td>
    <td></td>
  </tr>
</div>

在普通文档中,<tr>不能是 <div> 的 child ,所以浏览器只是将其删除。在 <template> ,该要求不存在。你会发现相同的,比如说,<div style="{{myStyle}}"> .在文档中,浏览器会丢弃 style属性,因为它的值无效;在<template>它不会。这就是 <template> 的原因对,嗯,模板很有用。

如果您想了解更多<template> s 被渲染,我建议阅读 section about it in the HTML spec .阅读起来并不容易,部分内容可能难以理解,但您一定会学到很多东西。

  1. Are certain JS methods or HTML attributes different or not available?

<template>元素有 content属性,指向上面讨论的 DocumentFragment。

关于javascript - 浏览器如何处理 <template> 标签 VS <div> 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50028946/

相关文章:

javascript - 使 highchart 成为动态数据驱动的

javascript - Angular 2 RC5 及更高版本 - 当没有路由匹配时如何显示错误页面?

javascript - 为什么 console.log Javascript 时,reverseString 打印 undefined

javascript - 删除/避免将目标链接添加到 URL

javascript - appendChild() 从导入的模板中删除内容

javascript - 如何使用 jquery/javascript 验证表单?

html - 如何将其中一列的文本居中

javascript - 检测鼠标位置并触发功能

javascript - 有没有办法使用 querySelector 来获取打开的影子 dom

javascript - 在文档片段: Failed to execute 'insertAdjacentHTML' on 'Element' : The element has no parent中