0
<html>
    <head>
        <link rel="stylesheet" href="my.css" />
    </head>
    <body>
        <iframe id="baidu-container" src="http://image.baidu.com/i?tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&fm=result&fr=&sf=1&fmq=1374487244324_R&pv=&ic=0&nc=1&z=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8&word=giant" frameborder="0">
        </iframe>
        <script type="text/javascript" src="my.js"></script>
    </body>
</html>

I would like to execute the script in my.js after this iframe has loaded completely. So what shoud i do? Thanks.

1
  • 1
    If you need the control to happen from the parent window, you can have an event listener for the load event on the iframe element which then accesses the content of the iframe. Do you use jQuery at all? Commented Jul 22, 2013 at 2:19

3 Answers 3

1
<html>
    <head>
        <link rel="stylesheet" href="my.css" />
    </head>
    <body>
        <iframe id="baidu-container" src="http://image.baidu.com/i?tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&fm=result&fr=&sf=1&fmq=1374487244324_R&pv=&ic=0&nc=1&z=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8&word=giant" frameborder="0">
        </iframe>
        <script>
          window.document.getElementById("baidu-container").onload = function() {
            var s = document.createElement("script");
            s.type = "text/javascript";
            s.src = "my.js";
            window.document.head.append(s);
          }
        </script>
    </body>
</html>
  1. Listen to the iframe load event.
  2. When the iframe document is loaded then add/execute your JavaScript code.
Sign up to request clarification or add additional context in comments.

Comments

1

Answering the question in the title. If the page inside the iframe is from another domain, you can't. Otherwise:

function addScript() {
  var iframeDoc = iframe.contentDocument;
  var s = iframeDoc.createElement('script');
  s.type = 'text/javascript';
  s.src = 'my.js';
  iframeDoc.body.appendChild(s);
}

// I'm creating the iframe programmatically, to make sure the onload handler fires.
var iframe = document.createElement('iframe');
iframe.width = 300;
iframe.height = 100;
iframe.onload = addScript;
iframe.src = "iframe-test2.html";
document.body.appendChild(iframe);

Comments

1

You can use the onload event on the iframe:

https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onload

2 Comments

link does not exist anymore
@robsch According to date this answer was post, probably was referring to this snapshot of w3schools. Suggested an edit in answer for this link.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.