JQuery – 等待加载两个iframe

我有一个按钮,可以在两个iframe中加载两个不同的页面。 我需要等待那些负载完成(比如ready(),不关心图像和其他内容),然后触发另一个动作。 我怎样才能做到这一点?

一种方法是让iFrame内容发出信号表明它已准备就绪。 这是一种简单的方法:

主页

var status = [false, false]; function doneLoading(index) { status[index] = true; if (status[1] && status[2]) alert("Both iframes are done loading"); } 

在每个iFrame中

 $(document).ready(function() { parent.doneLoading(1) }); // or 2 

使用$ .when()将帮助你(jQuery 1.5及更高版本)。 例如:

 function doAjax(){ return $.get('foo.htm'); } function doMoreAjax(){ return $.get('bar.htm'); } $.when( doAjax(), doMoreAjax() ) .then(function(){ console.log( 'I fire once BOTH ajax requests have completed!' ); }) .fail(function(){ console.log( 'I fire if one or more requests failed.' ); }); 

在我看来,最安全的解决方案可能是拥有一个嵌入两个iframe的父iframe,并等待加载整个页面(父页面):

 $(parent).load(function(){ ... //if you get there then the 2 iframes are already loaded } 

缺点是它有很多iframe