如何在asp.net用户控件中动态附加脚本标记

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

本文关键字:动态 脚本 控件 asp net 用户      更新时间:2023-09-26

我有用户控制(myUserControl.ascx)。因为我试图附加脚本标记并动态分配"src",然后检查onload和oneror事件,但它似乎不起作用。我正在点击按钮调用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");.

而且,这里没有"出错"的情况:脚本要么下载,要么不下载(无论出于什么原因:不可用、连接、服务器错误等)。如果它确实[下载]了,那么在执行/使用该脚本时可能发生的任何错误都与传输无关(这些错误应该像处理任何其他脚本错误一样处理),所以你在这里使用"oneror"的意图并不合适(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错误,这些错误通常指向不相关的位置。至少,缺少大括号属于这一类,因为这种语法错误实际上会完全"移动"(某种)代码块,使其无法弄清楚是什么。很抱歉这里有点跑题了。