2012-02-09 32 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错误,当你错过了一个大括号或由于其他语法错误而经常指向无关的位置。至少缺少一个括号是属于这个类别的,因为这样的语法错误实际上完全“转移”(某种类型)代码块,使得不可能弄清楚什么是什么。对不起,这里有点偏离主题。