Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making script wait until iframe has loaded before running

Tags:

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

I tried this:

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

And this:

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

But neither worked

like image 685
Jack Pilowsky Avatar asked Jul 02 '13 22:07

Jack Pilowsky


People also ask

Can you defer an iframe?

The loading attribute allows a browser to defer loading offscreen iframes and images until users scroll near them.

Do iframes slow down page load?

So, you should not use iframe excessively without monitoring what's going on, or you might end up harming your page performance. To avoid having your iframes slow down your pages, a good technique is to lazy load them (i.e., loading them only when they are required like when the user scrolls near them).

Does iframe load asynchronously?

Show activity on this post. One problem we had was that while iframes already do load asynchronously, the main page will not fire OnLoad until the iframe has finished loading too.


1 Answers

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

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

this works cross-browser.

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 }); 
like image 145
Yotam Omer Avatar answered Nov 11 '22 04:11

Yotam Omer