2012-02-09 30 views
0

我有用戶控制(myUserControl.ascx)。因爲我試圖追加腳本標記並動態分配「src」,然後檢查onload和onerror事件,但它似乎不工作。我在按鈕單擊時調用PerformDynamicJS。如何在asp.net用戶控件中動態添加腳本標記?

function PerformDynamicJS(){ 
var scriptGoogle = document.createElement("script"); 
scriptGoogle.type = "text/javascript"; 
scriptGoogle.src = "myscript.js"; 
scriptGoogle.onload = function (evt) { 
      alert('Inside onload'); 
     } 
scriptGoogle.onerror = function (evt) { 
      alert('Inside on error'); 
     } 
} 
+0

http://stackoverflow.com/questions/4117712/add-script-tag-within-head-tag-in-servercontrol-asp-net – Neha 2012-02-09 09:44:10

回答

1

新創建的標籤添加到文檔:

document.getElementsByTagName('head')[0].appendChild(scriptGoogle); 
+0

我不能得到我的頭標籤,因爲它不存在於我的用戶控制。它出現在我的母版頁中。 – 2012-02-09 09:34:34

+0

如果是用戶控件,則無關緊要。您可以從JavaScript功能「PerformDynamicJS」中訪問整個文檔。如果您的頁面上沒有部分,請使用「document.body」而不是「document.getElementsByTagName(...)」。 – volpav 2012-02-09 09:37:17

1
var script = document.createElement("script"); 
script.setAttribute("type", "text/javascript"); 
script.setAttribute("src", "url to the script file here"); 
document.getElementsByTagName("head")[0].appendChild(script); 

我看了「onload事件」與腳本之前,我不記得找到這樣的事件。我最終編寫了一個基於計時器的js代碼來經常檢查預期要在正在下載的腳本中定義的對象。因此,無論是你這樣做,還是:爲什麼不在插入腳本標籤的代碼中做任何事情 - 相反,當腳本準備就緒時,你有一個完美的時機:將「未包裝」代碼添加到腳本本身(例如alert("I, the script, loaded and I'm ready with these functions that I provide");

而且,這裏沒有「on error」情況:腳本將下載或不會(無論出於何種原因:不可用,連接性,服務器錯誤等)如果它[下載],當腳本正在執行/使用時可能發生的任何錯誤都不是真正的傳輸相關的(應該像對待任何其他腳本錯誤一樣對待那些錯誤),因此您在這裏使用「onerror」的意圖不是(IMO)+1 :)

編輯:如果它不下載,那麼它將不會執行,你將無法使用它。如果你的客戶端代碼真的在等待,那麼你將不得不編寫某種基於定時器的超時邏輯;例如,「添加到頭」上面行後,做這樣的事情:

window.setTimeout(function() 
{ 
    // object/variable "newScriptObject" is defined in the new script 
    if(!newScript) 
    { 
     // script timed out; let's proceed with plan B 
    } 
    else 
    { 
     // script ready, proceed as planned; 
     // although, like I said, I think it's more precise if you execute this code in your myscript.js instead - as maybe that code will be ready before the 5 sec assumed here 
     // alternatively, use window.setInterval to check for objects defined this script every so milliseconds, in which case, when you find the script, don't forget to stop that timer (window.clearInterval) 
    } 
}, 5000); // wait 5 sec for the new script 

最後,有沒有這樣的事情在這方面「部分下載」。一個理智的瀏覽器不會開始執行未完全執行的腳本,不僅會下載腳本,還會被解析(解釋)。 「解釋」部分就是爲什麼你會看到JS錯誤,當你錯過了一個大括號或由於其他語法錯誤而經常指向無關的位置。至少缺少一個括號是屬於這個類別的,因爲這樣的語法錯誤實際上完全「轉移」(某種類型)代碼塊,使得不可能弄清楚什麼是什麼。對不起,這裏有點偏離主題。