【发布时间】:2011-12-26 08:02:10
【问题描述】:
我们使用 ASP.NET 编写了 Portal。但是它有很多 Javascript,我们的页面加载速度很慢。 在某些页面中,页面大小为 1.5 mb! 减少或压缩页面大小以使其更快的最佳方法是什么? 谢谢
【问题讨论】:
-
有任何网格视图吗?检查您的视图状态大小,因为这可能是问题
标签: asp.net
我们使用 ASP.NET 编写了 Portal。但是它有很多 Javascript,我们的页面加载速度很慢。 在某些页面中,页面大小为 1.5 mb! 减少或压缩页面大小以使其更快的最佳方法是什么? 谢谢
【问题讨论】:
标签: asp.net
几件事:
if you can 或至少仅在需要它的控件上启用它。【讨论】:
另外,不要忘记ViewState。不需要时关闭它,它可以显着增加您的页面大小。
【讨论】:
你可以做很多不同的事情。任何简单的方法都是实现压缩。
在我的网站上,我的 web.config 文件中有这个:
<system.web>
<httpModules>
<add name="CompressionModule" type="Utility.HttpCompressionModule"/>
</httpModules>
</system.web>
这是 HttpCompressionModule:
public class HttpCompressionModule : IHttpModule
{
/// <summary>
/// Initializes a new instance of the <see cref="AjaxHttpCompressionModule"/> class.
/// </summary>
public HttpCompressionModule()
{
}
#region IHttpModule Members
/// <summary>
/// Disposes of the resources (other than memory) used by the module that implements <see cref="T:System.Web.IHttpModule"/>.
/// </summary>
void IHttpModule.Dispose()
{
}
/// <summary>
/// Initializes a module and prepares it to handle requests.
/// </summary>
/// <param name="context">An <see cref="T:System.Web.HttpApplication"/> that provides access to the methods, properties, and events common to all application objects within an ASP.NET application</param>
void IHttpModule.Init(HttpApplication context)
{
context.BeginRequest += (new EventHandler(this.context_BeginRequest));
}
#endregion
/// <summary>
/// Handles the BeginRequest event of the context control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
void context_BeginRequest(object sender, EventArgs e)
{
HttpApplication app = (HttpApplication)sender;
string encodings = app.Request.Headers.Get("Accept-Encoding");
Stream baseStream = app.Response.Filter;
if (string.IsNullOrEmpty(encodings))
return;
string url = app.Request.RawUrl.ToLower();
if (url.Contains(".js") || url.Contains(".css") || url.Contains("ajax.ashx"))
{
encodings = encodings.ToLower();
if (encodings.Contains("gzip") || encodings == "*")
{
app.Response.Filter = new GZipStream(baseStream, CompressionMode.Compress);
app.Response.AppendHeader("Content-Encoding", "gzip");
}
else if (encodings.Contains("deflate"))
{
app.Response.Filter = new DeflateStream(baseStream, CompressionMode.Compress);
app.Response.AppendHeader("Content-Encoding", "deflate");
}
}
}
}
也许你可以尝试类似的方法。
您可以做的另一件事是缩小您的 javascript 和 css。这意味着要做一些事情,比如用短变量名替换长变量名,并删除 cmets 和空格。您可以在构建脚本中包含执行此操作的内容。我的网站使用 python 作为它的构建脚本,它们很长而且很复杂,所以我不会在这里发布它们。 SO上有一个关于编写python脚本来缩小css的老问题,这可能会给你一个很好的起点:Link。
【讨论】: