jQuery .ready in a dynamically inserted iframe

后端 未结 10 2001
闹比i
闹比i 2020-11-22 07:11

We are using jQuery thickbox to dynamically display an iframe when someone clicks on a picture. In this iframe, we are using galleria a javascript library to display multip

10条回答
  •  清酒与你
    2020-11-22 07:41

    Following DrJokepu's and David Murdoch idea I implemented a more complete version. It requires jQuery on both the parent and iframe and the iframe to be in your control.

    iframe code:

    var iframe = window.frameElement;
    
    if (iframe){
        iframe.contentDocument = document;//normalization: some browsers don't set the contentDocument, only the contentWindow
    
        var parent = window.parent;
        $(parent.document).ready(function(){//wait for parent to make sure it has jQuery ready
            var parent$ = parent.jQuery;
    
            parent$(iframe).trigger("iframeloading");
    
            $(function(){
                parent$(iframe).trigger("iframeready");
            });
    
            $(window).load(function(){//kind of unnecessary, but here for completion
                parent$(iframe).trigger("iframeloaded");
            });
    
            $(window).unload(function(e){//not possible to prevent default
                parent$(iframe).trigger("iframeunloaded");
            });
    
            $(window).on("beforeunload",function(){
                parent$(iframe).trigger("iframebeforeunload");
            });
        });
    }
    

    parent test code:

    $(function(){
        $("iframe").on("iframeloading iframeready iframeloaded iframebeforeunload iframeunloaded", function(e){
            console.log(e.type);
        });
    });
    

提交回复
热议问题