簡體   English   中英

如何在asp.net用戶控件中動態附加腳本標記?

[英]How to append script tag dynamically in asp.net user control?

我有用戶控件(myUserControl.ascx)。 因為我試圖附加腳本標簽並動態分配“src”然后檢查onload和onerror事件,但它似乎無法正常工作。我在按鈕點擊時調用PerformDynamicJS。

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');
        }
}

將新創建的標記添加到文檔中:

document.getElementsByTagName('head')[0].appendChild(scriptGoogle);
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");

而且,這里沒有“錯誤”的情況:腳本將下載或不會(無論出於何種原因:不可用,連接,服務器錯誤等)。 如果它[下載],那個正在執行/使用該腳本時可能發生的任何錯誤都不是真正與傳輸相關的(這些錯誤應該被視為處理任何其他腳本錯誤的方式),所以你的意圖是“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錯誤,當你錯過任何地方的支撐或由於其他語法錯誤時,這些錯誤經常指向不相關的位置。 至少缺少一個大括號屬於這一類,因為這樣的語法錯誤實際上完全“轉移”(某種)代碼塊,使得無法弄清楚它是什么。 對不起,這里有點偏離主題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM