繁体   English   中英

使脚本等到iframe加载后再运行

[英]Making script wait until iframe has loaded before running

我正在处理的网站在iframe上有一个Live Chat插件。 如果没有可用的代理,我正在尝试更改图像。 我的代码在控制台上运行,但网站上没有任何内容。

var LiveChatStatus = $("iframe").contents().find(".agentStatus").html();
if (LiveChatStatus =="Offline"){
    $('#liveChat').html('<img src="%%GLOBAL_ShopPath%%/product_images/theme_images/liveoffline.png">');
}

我试过这个:

$('iframe').ready(function(){
    var LiveChatStatus = $("iframe").contents().find(".agentStatus").html();
    if (LiveChatStatus =="Offline"){
        $('#liveChat').html('<img src="%%GLOBAL_ShopPath%%/product_images/theme_images/liveoffline.png">');
    }
});

还有这个:

$(document).ready(function(){
   var LiveChatStatus = $("iframe").contents().find(".agentStatus").html();
   if (LiveChatStatus =="Offline"){
       $('#liveChat').html('<img src="%%GLOBAL_ShopPath%%/product_images/theme_images/liveoffline.png">');
   }
});

但都没有奏效

最好的解决方案是在父级中定义一个函数,例如function iframeLoaded(){...} ,然后在iframe中使用:

$(function(){
    parent.iframeLoaded();
})

这适用于跨浏览器。

如果您无法更改iframe中的代码,那么最佳解决方案是将load事件附加到iframe。

$(function(){
    $('iframe').on('load', function(){some code here...}); //attach the load event listener before adding the src of the iframe to prevent from the handler to miss the event..
    $('iframe').attr('src','http://www.iframe-source.com/'); //add iframe src
});

绑定到iframe的load事件的另一种方法是在向iframe添加src标记之前将加载侦听器附加到iframe。

这是一个简单的例子。 这也适用于您无法控制的iframe。

http://jsfiddle.net/V42ts/

// First add the listener.
$("#frame").load(function(){
    alert("loaded!");
});

// Then add the src
$("#frame").attr({
    src:"https://apple.com"
})

从Elijah Manor的网站上找到了这个,效果非常好

 function iFrameLoaded(id, src) { var deferred = $.Deferred(), iframe = $("<iframe class='hiddenFrame'></iframe>").attr({ "id": id, "src": src }); iframe.load(deferred.resolve); iframe.appendTo("body"); deferred.done(function() { console.log("iframe loaded: " + id); }); return deferred.promise(); } $.when(iFrameLoaded("jQuery", "http://jquery.com"), iFrameLoaded("appendTo", "http://appendto.com")).then(function() { console.log("Both iframes loaded"); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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