execv execv - 27 days ago 9
Javascript Question

jQuery: Detect iFrame not loaded after X sections

I'm loading an iFrame in a modal window from another domain, but sometimes the frame does not load, or takes 20+ seconds to load. Here is the code:

HTML:

<div id="mask">
<div id="iframe_lightbox">
<div id="iframe_container"><iframe id="patternCoolerIframe" style="width: 100%; height: 100%;" src="" frameborder="0" ></iframe></div>
<div id="iframe_lightbox_close">X</div>
</div>
</div>


JS:

function launch_iFrame(iframeSrc, iframeID){
$("#mask").fadeTo('500', 1, function () {

$('<iframe>', {
src: iframeSrc,
id: 'iframeID',
frameborder: 0,
scrolling: 'no',
width: '100%',
height: iFrameH+'px'
}).appendTo('#iframe_container');
});
}


How can I detect if the content has not loaded in the iframe after X seconds? I'd like to either display a message to the user, or to refresh the page.

Answer

You can use a timer and check if the onload handler has fired

function launch_iFrame(iframeSrc, iframeID){

    var timer = setTimeout(function() {
        alert('The iFrame didn\'t load in five seconds !');
    }, 5000);

    $("#mask").fadeTo('500', 1, function () {

        $('<iframe>', {
            src         : iframeSrc,
            id          : 'iframeID',
            frameborder : 0,
            scrolling   : 'no',
            width       : '100%',
            height      : iFrameH+'px',
            on          : {
                load : function() {
                    clearTimeout(timer); // remove timer when iFrame loads
                }
            }
         }).appendTo('#iframe_container');
     });
}
Comments