Man*_*ngo 5 html javascript templates html5-template
我最近发现了HTML template元素,希望对它进行一些澄清。
据我所知,这三个主要特征是:
template 没有呈现在屏幕上template 没有进入DOMcontent之间还有一个虚拟属性template除了这些之外,a <template>可能还被div隐藏在屏幕和DOM中。在这方面,用于利用的JavaScript template与尝试使用伪造JavaScript的JavaScript 相同div。
问题是,这正确吗?我问是因为:
谢谢
有一些主要区别:
元素中的脚本(<script>)不会立即执行。<template>
媒体内容(<audio>,<video>,<img>)在模板中就不会被加载 immedialtey。
相反,一旦将它们插入渲染的DOM树中,它们将被执行或加载。
querySelector()方法调用和CSS 选择器不会浏览的内容<template>,但您仍然可以通过使用querySelector()其content属性来访问其中的元素。
使用HTML5模板,您可以以文档片段的形式访问其所有内容,并使用appendChild()而不是Modifying将其插入DOM树中innerHTML。
<template>元素可以放置在<head>元素中。
您可以使用字符串.innerHTML或通过使用DocumentFragment 访问模板内容.content。
假冒所有这些行为是非常困难的。有一些polyfill可以部分地做到这一点。我建议Neovov的那个。
看这个说明性的例子:
//explore the content of the template
var script = T1.content.querySelector( 'script' )
console.log( script.innerHTML )
function insert() {
//insert the real templete
Target1.appendChild( T1.content.cloneNode( true ) )
//insert the fake template
Target2.innerHTML += D1.innerHTML
}Run Code Online (Sandbox Code Playgroud)
<template id=T1>
Real Template -
<script>console.log( 'executed at each insertion' )</script>
</template>
<div hidden id=D1>
Fake Template -
<script>console.log( 'executed only at parsing' )</script>
</div>
<button onclick="insert()">insert</button>
<div id=Target1><div>
<div id=Target2><div>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
938 次 |
| 最近记录: |