jQuery .ready in a dynamically inserted iframe

后端 未结 10 2045
闹比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:44

    This function from this answer is the best way to handle this as $.ready explicitly fails for iframes. Here's the decision not to support this.

    The load event also doesn't fire if the iframe has already loaded. Very frustrating that this remains a problem in 2020!

    function onIframeReady($i, successFn, errorFn) {
        try {
            const iCon = $i.first()[0].contentWindow,
            bl = "about:blank",
            compl = "complete";
            const callCallback = () => {
                try {
                    const $con = $i.contents();
                 if($con.length === 0) { // https://git.io/vV8yU
                    throw new Error("iframe inaccessible");
                 }
    
    
       successFn($con);
         } catch(e) { // accessing contents failed
            errorFn();
         }
      };
      const observeOnload = () => {
        $i.on("load.jqueryMark", () => {
            try {
                const src = $i.attr("src").trim(),
                href = iCon.location.href;
                if(href !== bl || src === bl || src === "") {
                    $i.off("load.jqueryMark");
                    callCallback();
                }
            } catch(e) {
                errorFn();
            }
        });
      };
      if(iCon.document.readyState === compl) {
        const src = $i.attr("src").trim(),
        href = iCon.location.href;
        if(href === bl && src !== bl && src !== "") {
            observeOnload();
        } else {
            callCallback();
        }
      } else {
        observeOnload();
      }
    } catch(e) {
        errorFn();
    }
    

    }

提交回复
热议问题