在当前脚本标签位置插入iframe? [英] Insert iframe at current script tag location?

查看:249
本文介绍了在当前脚本标签位置插入iframe?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个叫做小部件的东西,我想在当前位置插入该小部件(最终只是一个 iframe )的脚本标签。

I've got what we'll just call a "widget"...and I want to insert that widget (ultimately just an iframe) at the current location of the script tag.

所以你可能有:

<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();
}

如代码注释所述,做文档.body.appendChild(iframe)工作正常,但只需在文档末尾插入iframe。

And as noted in the code comment, doing document.body.appendChild(iframe) works fine, but just inserts the iframe at the very end of the document.

但是我真正想要的只需将iframe插入到脚本标签的正确位置即可。那个 document.body.appendChild(iframe)是我的尝试,但它从来没有做任何事情(没有iframe和没有错误)。

But what I really want to do is just insert the iframe right where the script tag is. That document.body.appendChild(iframe) is my attempt at it, but it literally just doesn't seem to do anything (no iframe and no errors).

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

So, how can I insert the iframe in the same spot as the script tag?

推荐答案

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

You need to get the current <script> tag, which in this case is the last one:

var thisScript = document.scripts[document.scripts.length - 1];

插入< iframe> 之后:

var parent = thisScript.parentElement;
parent.insertBefore(iframe, thisScript.nextSibling);

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

或者只是 替换 当前脚本与< iframe>

var parent = thisScript.parentElement;
parent.replaceChild(iframe, thisScript);

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

另外 - 如果你可以相信它 - document.write () 实际上是一个合适的解决方案,只要您在文档加载而不是 window.onload callback:

Alternately – if you can believe it – document.write() is actually a suitable solution here, so long as you do it while the document is loading and not in a window.onload callback:

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

createIframe();

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

这篇关于在当前脚本标签位置插入iframe?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆