不能 运行 模板中的 IIFE

Cant run an IIFE inside a template

我正在使用 <template> 元素,但其中的 javascript 代码不会 运行。我正在使用 IIFE 立即 运行ning 获取它,但没有成功。

<div id="content">
  initial text
</div>

<template>
  <script>
    (function(){
        document.querySelector('#content').innerHTML = 'new text';
    })();
  </script>
</template>

模板内容不会呈现给 DOM,因此脚本不会 运行。

来自DOCS(第一段):

The HTML element is a mechanism for holding client-side content that is not to be rendered when a page is loaded but may subsequently be instantiated during runtime using JavaScript.

编辑
根据您对如何 运行 代码的评论,有几种方法。最简单的方法是抓住它的内容并将其放入 DOM:

<div id="content">
  initial text
</div>


<template>
  <script>
    (function(){
        document.querySelector('#content').innerHTML = 'new text';
    })();
  </script>
</template>

<script>
   var content = document.querySelector('template').content;
   document.body.appendChild(content,true);
</script>