Making script wait until iframe has loaded before

2020-02-10 03:23发布

问题:

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

回答1:

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


回答2:

Another way to bind to the load event of an iframe is to attach a load listener to the iframe before adding a src tag to the iframe.

Here's a simple example. This will also work with iframes that you don't control.

http://jsfiddle.net/V42ts/

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

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


回答3:

Found this from Elijah Manor's website which works very well

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>