privatestaticSortedList<int,string>GetRegisteredScriptIncludes()
{
var registeredScriptIncludes =System.Web.HttpContext.Current.Items["RegisteredScriptIncludes"]asSortedList<int,string>;
if(registeredScriptIncludes ==null)
{
registeredScriptIncludes =newSortedList<int,string>();
System.Web.HttpContext.Current.Items["RegisteredScriptIncludes"]= registeredScriptIncludes;
}
return registeredScriptIncludes;
}
publicstaticvoidRegisterScriptInclude(thisHtmlHelper htmlhelper,string script)
{
var registeredScriptIncludes =GetRegisteredScriptIncludes();
if(!registeredScriptIncludes.ContainsValue(script))
{
registeredScriptIncludes.Add(registeredScriptIncludes.Count, script);
}
}
publicstaticstringRenderScripts(thisHtmlHelper htmlhelper)
{
var registeredScriptIncludes =GetRegisteredScriptIncludes();
var scripts =newStringBuilder();
foreach(string script in registeredScriptIncludes.Values)
{
scripts.AppendLine("<script src='"+ script +"' type='text/javascript'></script>");
}
return scripts.ToString();
}
然后
<%
Html.RegisterScriptInclude(Url.Content("~/Scripts/my.js"));
%>
最后在body中相应的位置添加下面这句
<%=Html.RenderScripts() %>
///////////////////////////////////////////////
直接通过 javascript 来注册脚本
<scripttype="text/javascript"src="somescript.js"></script>
相当于
var script = document.createElement('script');
script.type ='text/javascript';
script.src ='somescript.js';
$('#someElement').append(script);