开发者

How to run dynamically loaded js file in iframe?

开发者 https://www.devze.com 2022-12-21 23:38 出处:网络
I have the following: $(document).ready(function() { var myIframe = document.getElementById(\'myIframe\');

I have the following:

$(document).ready(function() {

  var myIframe = document.getElementById('myIframe');
  var element = myIframe.开发者_如何学PythoncontentDocument.createElement('script');  
  element.setAttribute('src', '/javascripts/library/jquery/jquery.min.js');  
  myIframe.contentWindow.document.getElementsByTagName('head')[0].appendChild(element);

  $('#myIframe', top.document).load(function() {
    alert('iframe has loaded');

    var element = document.getElementById('myIframe').contentDocument.createElement('script');  
    element.setAttribute('src', '/javascripts/stuff.js');  
    myIframe.contentWindow.document.getElementsByTagName('body')[0].appendChild(element);  
  });

});

I get an alert of "iframe has loaded."

stuff.js contains

$('body').css('backgroundColor', 'yellow');

So, I would expect that the iframe's background color would change to yellow when the iframe has loaded...but nothing happens. I even tried surround what's in stuff.js in a $(document).ready block but had the same results.

If I select all and view source for the iframe, I see that jquery.min.js and stuff.js are in the iframe's . If I put this source output into a separate html file and run that, the document's background color changes as expected.

How can I get my javascript in stuff.js to run in the iframe once the iframe has loaded?


You can also do it in a more jQuery way.

$('<script/>', {
    src: '/path/to/javascript.js',
    type: 'text/javascript'
}).appendTo($('#iframe').contents().find('body'));


Hell yeah, I figured it out!

Turns out it was not working because I had set myIframe.contentDocument.designMode to "on". Commenting that out made it work. Hopefully I can turn it on after stuff.js has loaded and all will be well.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号