【问题标题】:How to append script tag dynamically in asp.net user control?如何在 asp.net 用户控件中动态附加脚本标记?
【发布时间】:2012-02-09 19:16:50
【问题描述】:

我有用户控制 (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');
        }
}

【问题讨论】:

标签: javascript asp.net dynamic onload onerror


【解决方案1】:

将新创建的标签添加到文档中:

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

【讨论】:

  • 我无法获取我的 head 标签,因为它不在我的用户控件中。它出现在我的母版页中。
  • 不管是不是用户控件。您可以从您的 JavaScript 函数“PerformDynamicJS”中访问整个文档。如果您的页面上没有 部分,请使用“document.body”而不是“document.getElementsByTagName(...)”。
【解决方案2】:
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 错误。至少缺少大括号属于这一类,因为这样的语法错误实际上会完全“转移”(某种)代码块,从而无法弄清楚是什么。抱歉,这里有点跑题了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-20
    • 1970-01-01
    相关资源
    最近更新 更多