我有一个有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!
答案 0 :(得分: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>