html5 templates,HTML Templates JavaScript polyfills

Xotic750 offered a solid polyfill that works by mutating HTML elements — but it will fail if any new templates are later added to the DOM, and mutation is increasingly discouraged (where avoidable).

Instead, I recommend introducing the "polyfill" behaviour at the point where you use the templates. Add this function to your JS:

function templateContent(template) {

if("content" in document.createElement("template")) {

return document.importNode(template.content, true);

} else {

var fragment = document.createDocumentFragment();

var children = template.childNodes;

for (i = 0; i < children.length; i++) {

fragment.appendChild(children[i].cloneNode(true));

}

return fragment;

}

}

Call the function with a reference to your template element. It'll extract the content, and return a documentFragment that you can then attach to another element (or do whatever else you might want to do with the template content). Like this:

var template = document.querySelector("template#my-template");

var content = templateContent(template);

someElm.appendChild(content);

Now, the other answer didn't mention it, but you probably want some CSS to hide the element.

template { display: none; }

Here's a CodePen that puts it all together.

Now, this will work correctly in browsers that natively support the element, and in those that don't. Similar to the other answer, it's not a perfect polyfill, since it doesn't render templates inert (that'd be complex, slow, and error-prone). But it works well enough for me to use in production.

Leave a comment if you've got questions or issues, and I'll revise accordingly.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值