在当前脚本标记位置插入iframe?

Shp*_*ord 7 javascript dom

我已经得到了我们称之为"小部件"的东西......我想iframe在脚本标签的当前位置插入该小部件(最终只是一个).

所以你可能有:

<p>Some example text</p>
<script src="http://example.com/widget.js" class="widget" async></script>
<p>More text</p>
Run Code Online (Sandbox Code Playgroud)

在该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();
}
Run Code Online (Sandbox Code Playgroud)

并且如代码注释中所述,document.body.appendChild(iframe)工作正常,但只是在文档的最末端插入iframe.

但我真正想要做的只是在脚本标记所在的位置插入iframe.这document.body.appendChild(iframe)是我的尝试,但它实际上似乎没有做任何事情(没有iframe,没有错误).

那么,如何将iframe插入与脚本标记相同的位置?

Mat*_*all 14

您需要获取当前<script>标记,在这种情况下是最后一个标记:

var thisScript = document.scripts[document.scripts.length - 1];
Run Code Online (Sandbox Code Playgroud)

插入<iframe>后:

var parent = thisScript.parentElement;
parent.insertBefore(iframe, thisScript.nextSibling);
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/mattball/Tz75x/

或者只需用以下内容替换当前脚本<iframe>:

var parent = thisScript.parentElement;
parent.replaceChild(iframe, thisScript);
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/mattball/a23XE/


或者 - 如果你可以相信它 - document.write()实际上是一个合适的解决方案,只要你在文档加载时而不是在window.onload回调中这样做:

function createIframe() {
    document.write('<iframe src="//example.com"></iframe>');
}

createIframe();
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/mattball/2YCcP

  • 感谢您的单挑,但我完全不赞成在我编写的任何代码中支持遗留IE.[jQuery 2于2013年4月发布](http://blog.jquery.com/2013/04/18/jquery-2-0-released/)并且不支持IE <9.是时候继续前进了. (3认同)