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

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

问题描述

我正在处理的网站在 iframe 上有一个实时聊天插件.如果没有可用的代理,我正在尝试更改图像.我的代码在控制台上工作,但在网站上没有.

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

但都没有效果

推荐答案

最好的解决方案是在你的父级中定义一个函数,例如 function 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 中的代码,最好的解决方案是将 load 事件附加到 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天全站免登陆