【问题标题】:Load event triggers server side script before script has loaded加载事件在脚本加载之前触发服务器端脚本
【发布时间】:2012-10-19 11:17:00
【问题描述】:

我有一个具有 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!

【问题讨论】:

  • 如何“加载服务器端脚本”?
  • 嗨,脚本声明如下:&lt;SCRIPT id=custom_scripts type=text/javascript src="htmlpathsub/custom/custom_scripts.js" UserSuppliedFullPath="1"&gt;&lt;/SCRIPT&gt;
  • 而外部脚本包含在 iframe 之前的 html 中?
  • 您能发布您的完整(或至少更多)html 和 javascript 吗?很难从那个 sn-p 看出发生了什么。

标签: javascript


【解决方案1】:

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

如果框架在外部脚本可用之前加载,您可以在加载外部脚本的元素上使用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>

【讨论】:

    猜你喜欢
    • 2011-01-30
    • 2023-04-04
    • 1970-01-01
    • 2015-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多