Making script wait until iframe has loaded before running

后端 未结 3 1720
一个人的身影
一个人的身影 2020-12-16 11:27

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 t

相关标签:
3条回答
  • 2020-12-16 12:14

    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"
    })
    
    0 讨论(0)
  • 2020-12-16 12:21

    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
    });
    
    0 讨论(0)
  • 2020-12-16 12:23

    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>

    0 讨论(0)
提交回复
热议问题