使用template元素插入含script标签的HTML字符串时仅首个script生效问题
问题原因与解决方法
你遇到的问题出在htmlToElement函数的返回值上:函数最后返回template.content.firstChild,这只会取出模板解析后的第一个子元素(也就是第一个<script>标签),后面的<ins>和第二个<script>都被直接忽略了,所以最终只有第一个script被添加到.a元素中。
解决方法
修改htmlToElement函数,返回整个模板的内容片段(DocumentFragment),这样就能包含所有解析后的子元素:
var adContent = '<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"><\/script><ins class="adsbygoogle" style="display:inline-block;width:728px;height:90px" data-ad-client="AD_CLIENT_HERE" data-ad-slot="AD_SLOT_HERE"></ins><script>(adsbygoogle = window.adsbygoogle || []).push({});<\/script>' 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
相关产品推荐
相关产品推荐

