在Asp.Net开发时,用到的JS库、通用的CSS等,在很多页面都会用到,而每次都须要手动引入。相当麻烦。并且有时一旦忘了引用,还得找半天才干找到问题。那有没有什么办法可以一劳永逸的呢?答案是有的。
我们知道Asp.Net是可以通过后台来渲染前端的。所以假设可以在渲染时将所要的js库和css等添入就行了。而为了可以复用,所以须要进行类的继承。我们写一个Page的基类PageBase,代码例如以下。
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Text; namespace AspNetLoadJsCss.Common { public class PageBase : System.Web.UI.Page { public static readonly string SCRIPT_INCLUDE_TEMPLATE = "<script src="{0}" type="text/javascript"></script> "; public static readonly string STYLE_INCLUDE_TEMPLATE = " <link href="{0}" rel="stylesheet" type="text/css"/> "; public static readonly string SCRIPT_CONTENT_TEMPLATE = "<script type="text/javascript">{0}</script> "; protected void Page_InitComplete(object sender, EventArgs e) { LiteralControl viewportControl = new LiteralControl(); viewportControl.ID = "viewport"; viewportControl.Text = " <meta name="viewport" content="width=device-width, initial-scale=1" />"; this.Header.Controls.AddAt(GetNextControlIndex(this), viewportControl); LiteralControl jqueryCssControl = new LiteralControl(); jqueryCssControl.ID = "/jquery.mobile-1.4.4.min.css"; jqueryCssControl.Text = String.Format(STYLE_INCLUDE_TEMPLATE, "/css/themes/default/jquery.mobile-1.4.4.min.css"); this.Header.Controls.AddAt(GetNextControlIndex(this), jqueryCssControl); LiteralControl myCssControl = new LiteralControl(); myCssControl.ID = "/my.css"; myCssControl.Text = String.Format(STYLE_INCLUDE_TEMPLATE, "/css/my.css"); this.Header.Controls.AddAt(GetNextControlIndex(this),myCssControl); String jsPath = "/js/jquery.js"; this.ClientScript.RegisterStartupScript(this.GetType(), "jquery", String.Format(SCRIPT_INCLUDE_TEMPLATE, jsPath), false); jsPath = "/js/jquery.mobile-1.4.4.