我可以为您提供帮助,以下是我翻译的结果:
在那个
我有一个我们称之为“小部件”的东西...... 我想在脚本标记的当前位置插入该小部件(最终只是一个 iframe
)。
所以你可能会有:
<p>Some example text</p>
<script src="http://example.com/widget.js" class="widget" async></script>
<p>More text</p>
在那个
widget.js
文件中,有这样一段代码:var createIframe = function() {
var parent = document.getElementsByClassName('widget');
var iframe = document.createElement('iframe');
iframe.src = '//example.com'
// Works, but just inserts it at the end
document.body.appendChild(iframe);
// Does not work...just doesn't seem to do anything
document.createElement("div").appendChild(iframe);
}
window.onload = function() {
createIframe();
}
正如代码注释中所提到的那样,使用document.body.appendChild(iframe)
可以正常工作,但只会将 iframe 插入到文档的末尾。
我真正想做的是将 iframe 直接插入到脚本标签所在的位置。我尝试了 document.body.appendChild(iframe)
,但它似乎什么也没做(没有 iframe 也没有错误)。
那么,我该如何将 iframe 插入到与脚本标签相同的位置呢?
document.currentScript
来获取加载当前脚本的确切脚本标签。支持除 IE 以外的所有浏览器 -> https://caniuse.com/document-currentscript - hiddentao