Run script before iframe loads

狂风中的少年 提交于 2019-12-12 18:27:32

问题


I'm working with a help system which is embedded in an application.

The important part of the help tries to have the same document.domain value, but the child iframe seems to run its document.domain setting before the parent does. This is a problem because it throws a security error and halts javascript execution. Here's basically what the html looks like, to give the proper idea:

<html>
    <head>
        <!--Occasionally runs second-->
        <script src="change-document-domain.js"></script>
    </head>

    <body>
        <iframe>
            <html>

                <head>
                    <!--Occasionally runs first-->
                    <script src="change-document-domain.js"></script>
                </head>

            </html>
        </iframe>
    </body>
</html>

The help is very restricted by the program which builds it. Is there any change I can make to the parent script or parent script tag to make it load before the iframe or its script does?

Let me know if you have any questions, and thanks as always!


回答1:


One thing that you can do is set the source of the iFrame after the script loads.

So, create a function that will load the script on page load, and then once the scrip is completed you can set a callback function which will execute after your script is done loading.

function loadScript( url, callback ) {
  var script = document.createElement( "script" )
  script.type = "text/javascript";
  if(script.readyState) {  //IE
    script.onreadystatechange = function() {
      if ( script.readyState === "loaded" || script.readyState === "complete" ) {
        script.onreadystatechange = null;
        callback();
      }
    };
  } else {  //Others
    script.onload = function() {
      callback();
    };
  }

  script.src = url;
  document.getElementsByTagName( "head" )[0].appendChild( script );
}


// call the function...
loadScript('change-document-domain.js', function() {
  //executes after the script is laoded.
  document.getElementById("myFrame").src = "sourceOfIFrame.html"
});



回答2:


Not sure about whether you want this kind of solution or not. But using javascript or jquery for this purpose might be a workaround.

<iframe id="frame" src="">
</iframe>

And you just trigger the iFrame load after the parent content javascript is loaded ...

 $("#frame").prop("src", "http://iframe-url.com/");



回答3:


try creating a separate page containing the content for the iframe and like to it, which could be slightly slower, but would load in order.



来源:https://stackoverflow.com/questions/23742344/run-script-before-iframe-loads

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!