使脚本等到iframe加载后再运行 [英] Making script wait until iframe has loaded before running

查看:561
本文介绍了使脚本等到iframe加载后再运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The site I'm working on has a Live Chat plugin on an iframe. I'm trying to change an image if there are no agents available. My code works on the console, but nothing on the site.

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">');
   }
});

但两种方式都不起作用

推荐答案

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

The best solution is to define a function in your parent such as function iframeLoaded(){...} and then in the iframe use:

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

这适用于跨浏览器。

如果您无法更改iframe中的代码,您最好的解决方案是将加载事件附加到iframe ..

If you cannot change the code within the iframe, your best solution will be to attach the load event to the 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加载后再运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆