You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用template元素插入含script标签的HTML字符串时仅首个script生效问题

问题原因与解决方法

你遇到的问题出在htmlToElement函数的返回值上:函数最后返回template.content.firstChild,这只会取出模板解析后的第一个子元素(也就是第一个<script>标签),后面的<ins>和第二个<script>都被直接忽略了,所以最终只有第一个script被添加到.a元素中。

解决方法

修改htmlToElement函数,返回整个模板的内容片段(DocumentFragment),这样就能包含所有解析后的子元素:

var adContent = '&lt;script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"&gt;&lt;\/script&gt;&lt;ins class="adsbygoogle" style="display:inline-block;width:728px;height:90px" data-ad-client="AD_CLIENT_HERE" data-ad-slot="AD_SLOT_HERE"&gt;&lt;/ins&gt;&lt;script&gt;(adsbygoogle = window.adsbygoogle || []).push({});&lt;\/script&gt;'

var a = document.querySelector('.a'),
    ad = htmlToElement(adContent)

a.append(ad)

function htmlToElement (html) {
    var template = document.createElement('template');
    html = html.trim(); 
    template.innerHTML = html;
    return template.content; // 返回完整的文档片段,包含所有子元素
}

当你调用a.append(ad)时,文档片段里的所有元素(两个<script>和<ins>)都会被插入到.a中,和直接使用innerHTML的效果一致。

补充说明:<template>中的<script>不会在解析时执行,但插入到DOM后,外部加载的script会正常异步加载,第二个初始化脚本也会在DOM中执行,符合广告代码的预期逻辑。

内容的提问来源于stack exchange,提问作者Toniq

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 15:10:26