2012-10-19 29 views
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!

+1

你如何「加載服務器端腳本」? – Bergi

+0

嗨,腳本是這樣聲明:'' – Needaf1x

+0

而外部腳本包含進來的HTML在iframe之前? – Bergi

回答

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>