简体   繁体   中英

How to know when an iframe is ready?

I have an iframe inside a web page, and I want to do something when it is ready. I tried 2 ways:

  • In the parent page, I use this

     jQuery('#iframe').load(function() { //my code here }); 

this code will be executed when the iframe is finished loading (as I wanted), but because my iframe is pointed to another domain, so at this point, I can't access its content (cross domain problem)

  • Inside the iframe, I use this:

      jQuery('body').ready(function() { }); 

This code is executed when the iframe starts loading, which is much earlier than I want, so the code can not function properly.

So how I execute code when the iframe is finished loading and ready for DOM-manipulation

I searched and found that easyXDM may be the solution, but I wonder if there is simpler solution exists.

Thank you.

underscore has a handy defer method I've used for things like this, try:

$('#iframe').load(function() { 
    _.defer(function(){
        //your code here 
    });
});

dont't use jquery,It will make your javascript knowledge confusion,

You can use the following code

<script type="text/javascript">
    function show(){
        var iframe=document.getElementById('aa');
        var h=iframe.contentWindow.document.body.offsetHeight;
        alert(h)    
    }
</script>
</head>
<body>
<iframe id="aa" src="3.html" frameborder="0" scrolling="no" width="100%" height="200" onload="show()"></iframe>
</body>

Since you want to know when the iframe is ready AND you want to access content from that iframe cross-domain, I think easyXDM would be a good choice.

You could basically implement this example , and simply add your code to the "onReady" method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM