Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
236 views
in Technique[技术] by (71.8m points)

javascript - Insert iframe at current script tag location?

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.

So you might have:

<p>Some example text</p>
<script src="http://example.com/widget.js" class="widget" async></script>
<p>More text</p>

In that widget.js file, there is this:

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

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.

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).

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

and insert the <iframe> after it:

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

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

Or simply replace the current script with the <iframe>:

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

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


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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...