سؤال

I wanted to use the HTML 5 template tag but there's some confusing behaviour after a page refresh. Maybe I show you some code first:

<!doctype html>
<meta charset=utf-8>
<title>HTML 5 - template test</title>

<template>
    <h1>This is an awesome new HTML 5 template</h1>
    <p>.. some even more awesome content .. some even more awesome content .. some even more awesome content .. some even more awesome content .. some even more awesome content</p>
</template>
<div></div>

<script>
var template = document.querySelector('template'),
    templateContent = template.content.cloneNode(true);

console.log(template);
console.log(templateContent);

document.querySelector('div').appendChild(templateContent);
</script>

Actually this works as expected, but there's some confusing stuff going on in the console. When I first open the page it says:

http://i.stack.imgur.com/xDJBo.png

but when I refresh the page it shows up this:

http://i.stack.imgur.com/W23YF.png

When I repeat it I see the stuff from the first picture again. I tried it also on jsbin and there I can't see this behaviour: http://jsbin.com/ofotah/1

I have really no idea what is going on there. I'm using Google Chrome Version 27.0.1453.110 (Windows). Hope you can help me with this.

هل كانت مفيدة؟

المحلول

This isn't really template related, it's a funky Chrome quirk that manifests sometimes. It'll do the same for other element tags under conditions that are virtually impossible to reproduce, but the actual object content is never affected. It just sometimes grabs the toString() serialization, and sometimes the object serialization.

However, as Andbdrew points out, the template tag is still a draft element, and we're far from any decision on how it should be user properly or how to access them, so given how your example code uses it, I'd recommend just using a <script type="text/template">...</script> element instead, and selecting it with document.querySelector("script[type='text/template']"); rather than using an experimental element =)

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top