Where can I find a Web application that does not introduce JavaScript script files? There is a lot of benefit in using script files, the most important of which is the ability to provide caching. After using the script file plus caching, you can greatly reduce the amount of data transfer, improve the speed of page opening. However, the introduction of the script file is not trivial, we are fully capable of optimizing it.
Be careful about the performance problems of the traditional scripting introduction
More and more scripts are needed for Web apps today, and a page download of hundreds of K scripts is no longer unthinkable, which directly results in a longer time for the page to load the script. But what is the problem with the traditional scripting approach (using <script/>)? Before we look at this, we'll write a HttpHandler to simulate a script that takes a long time to load. It's simple, we just create an HTTP handler to do this, as follows:
Scripts.ashx
public class Scripts : IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "application/x-javascript";
System.Threading.Thread.Sleep(1500);
context.Response.Write("//");
}
public bool IsReusable {
get {
return false;
}
}
}
I use the Thread.Sleep function to keep a thread dormant for 1.5 seconds, and then output an annotation character. This ensures that the page loads the file for a long time or minimizes the execution time of the script.
Then we'll write the simplest page to test the results of loading these files:
Title
<title>Untitled Page</title>
<script type="text/javascript" language="javascript" src="Scripts.ashx?a"></script>
<script type="text/javascript" language="javascript" src="Scripts.ashx?b"></script>
<script type="text/javascript" language="javascript" src="Scripts.ashx?c"></script>
<script type="text/javascript" language="javascript" src="Scripts.ashx?d"></script>
<script type="text/javascript" language="javascript" src="Scripts.ashx?e"></script>
<body>
...
</body>
Open the page in IE to see how these scripts are loaded. Please note that you can use IE Dev toolbar to disable the cache (Figure 5).
Figure 5:ie the traditional way of loading scripts