2

我有一个具有 onload 事件的 iframe。此事件称为我放入服务器端脚本的函数 (iframe_load)。看来,当我的屏幕启动时,在服务器端脚本加载之前触发了 onload 事件,并且由于找不到该函数而出现错误。

我通过更改 onload 事件以在客户端脚本中调用检查函数 (iframe_check_load) 解决了这个问题。这将检查服务器端脚本中是否存在参数,如果找到,它将调用原始函数 (iframe_load)。

但是理想情况下,我不希望有这个检查功能并将客户端代码保持在最低限度。有没有办法可以在 onload 事件中添加一些代码来执行此检查,而无需使用检查功能?

我当前的代码:

function iframe_check_load(ctrl) {
   if(typeof iframe_flag != "undefined"){
     iframe_load();                               
   }            
}

<IFRAME id=iFrame2 onload=iframe_check_load() ></IFRAME>

我相信一定有更好的方法来做这一切,请放轻松,因为我还在学习 JS!

4

1 回答 1

0

由于无法保证脚本在帧之前加载,反之亦然,因此必须至少执行一项检查,以了解在加载帧时外部脚本是否已经可用。

如果框架在外部脚本可用之前加载,您可以使用ONLOAD加载外部脚本的元素上的属性来通知它已经加载。这将确保iframe_load始终调用 。假设没有网络错误。

<SCRIPT>
//the saved "ctrl" parameter for iframe_load if
//the frame is loaded before custom_scripts.js.
var ctrlParam; //undefined as default

//script loaded handler for custom_scripts.js
function customScriptLoaded() {
    //call iframe_load only if ctrlParam is not undefined.
    //i.e.: frame is already loaded.
    //will do nothing otherwise. leave it to iframe_check_load.
    if (typeof ctrlParam != "undefined") {
        iframe_load(ctrlParam);
    }
}

//check whether it's safe to call iframe_load.
//assuming that "iframe_flag" is defined by custom_scripts.js.
function iframe_check_load(ctrl) {
    if (typeof iframe_flag != "undefined") {
        //custom_scripts.js already loaded.
        //call iframe_load now.
        iframe_load(ctrl);
    } else {
        //custom_scripts.js not yet loaded.
        //save parameter and defer call to iframe_load.
        //iframe_load will be called by customScriptLoaded.
        //ctrl parameter must not be undefined in order to work.
        console.log('Error: ctrl parameter of iframe_check_load is undefined. iframe_load will never be called.');
        ctrlParam = ctrl;
    }
}
</SCRIPT>

<!--Note: Don't forget to duble-quotes attribute values-->
<SCRIPT id="custom_scripts" type="text/javascript" src="htmlpathsub/custom/custom_scripts.js" UserSuppliedFullPath="1" onload="customScriptLoaded()"></SCRIPT>

<!--Using "this" (the IFRAME element) as the "ctrl" parameter-->
<IFRAME id="iFrame2" onload="iframe_check_load(this)"></IFRAME>
于 2012-10-19T14:57:17.980 回答