Make Ajax calls take advantage of caching features

Source: Internet
Author: User
Tags browser cache server memory
<span id="Label3"></p>Optimize Web site design (14): make Ajax calls as far as possible using the caching features foreword<p><p>Optimization of website design is a big topic, there are some common principles, and there are some suggestions for different development platforms. This research has never stopped, and I have shared such topics on different occasions.</p></p><p><p>As a general rule, Yahoo's team of engineers has given 35 best practices. For this list, please refer to best <strong>practices for speeding up Your Web Site </strong>http://developer.yahoo.com/performance/ rules.html, at the same time, they also released a corresponding test tool YSlow http://developer.yahoo.com/yslow/</p></p><p><p>I strongly recommend that all Web developers learn these best practices and apply them in conjunction with their actual project Scenarios. For the next period of time, I will combine the asp. net this development platform, in accordance with these principles, through a series of articles in the form of some explanation and interpretation, to help you better understand these principles, and to better use Them.</p></p>Preparatory work<p><p>In order to follow my follow-up study, you need to prepare the following development environment and tools</p></p> <ol> <ol> <li>Google Chrome or firefox, and install the YSlow Extension. Please note that this component is provided by yahoo, but there is currently no version for Ie. <ol> <li>Https://chrome.google.com/webstore/detail/yslow/ninejjcohidippngpapiilnmkgllmakh</li> <li>https://addons.mozilla.org/en-US/firefox/addon/yslow/</li> <li>You should be aware of the developer tools of these browsers, you can call this tool by pressing the F12 key.</li> </ol></li> <li>Visaul Studio SP1 or later, we recommend that you use Visual Studio 2012 <ol> <li>Http://www.microsoft.com/visualstudio/eng/downloads</li> </ol></li> <li>You need to have a good understanding of the basic process and core technologies of asp. this series of articles is difficult to popularize the basic knowledge.</li> </ol> </ol>The topic to be discussed in this paper<p><p>In this article, I'm talking about the 14th principle: make Ajax cacheable (making Ajax calls take advantage of the caching features as much as possible).</p></p>The basic concept of Ajax <ol> <ol> <li>AJAX = asynchronous JavaScript and XML (asynchronous JavaScript and xml).</li> <li>AJAX is not a new programming language, but a new method of using existing STANDARDS.</li> <li>AJAX is the art of exchanging data with a server and updating parts of a Web page without reloading the entire page.</li> </ol> </ol>Typical application scenarios for Ajax<p><p>Ajax is widely used in current applications, providing richer results for the site (although the technology is very early, it was first noticed in Gmail in about 2004 years). Typical application scenarios include</p></p> <ol> <ol> <li>Asynchronous loading, so that the contents of the page can be loaded in Batches.</li> <li>Partial updates, which make local updates to the page do not cause the page to Refresh.</li> </ol> </ol><p><p>Since Ajax actually needs to initiate a request, and then the server executes and sends the result (usually in JSON Format) to the browser for final rendering or processing, we also need to consider whether these requests can be used as much as possible to improve performance in terms of site design Optimization.</p></p><p><p>"remarks" about ajax, and how it combines with some of the current technologies (primarily Server-side technologies), I've written a lot before, and interested friends can refer to http://www.google.ee/search?q=site% First. 3awww.cnblogs.com%2fchenxizhang%2f%20ajax</p></p>What kind of Ajax requests can be cached?<p><p>There are a number of ways to optimize server requests, and I've written several before, and these principles can be applied in Ajax Scenarios.</p></p> <ol> <ol> <li><span style="font-size: small;">Optimize website design (iii): Add cache control to resources</span></li> <li><span style="font-size: small;">Optimize Web site design (iv): enable compression on resources</span></li> <li><span style="font-size: small;">Optimize website Design (ix): Reduce the number of DNS lookups</span></li> <li><span style="font-size: small;">Optimize website design (10): minimize JavaScript and CSS</span></li> <li><span style="font-size: small;">Optimize website design (11): avoid redirects</span></li> <li><span style="font-size: small;">Optimize website design (13): Configure Etags</span></li> </ol> </ol><p><p>however, for ajax, There are some peculiarities, and not all AJAX requests can be Cached. This is due to the fact that Ajax requests typically have two different methods: post and Get. They are slightly different when they make the Request.</p></p> <ol> <ol> <li><strong><span style="color: #ff0000;">Post requests are not cached on the client</span></strong> , and each request needs to be sent to the server for processing, and the status code 200 is returned each Time. (here you can optimize the Server-side caching of data to improve processing speed)</li> <li><strong><span style="color: #ff0000;">get requests, which can be cached by the client (and by Default)</span></strong> , unless a different address is specified, the AJAX request of the same address is not repeated on the server, but instead returns 304.</li> </ol> </ol><p><p></p></p>How to optimize for post<p><p>Post request, The browser usually assumes that the user wants to submit (or send) the data to the server, so the browser naturally does not cache the request because you are committing the data, so it thinks that the server is naturally required to handle it every Time. We can look at an example.</p></p><pre class="csharpcode"><span class="kwrd">Using System;<span class="kwrd">Using System.Web.Services;<span class="kwrd">Namespace webapplication4{<span class="rem"><span class="rem"> <span class="rem">//<summary>//summary description for Hellowebservice <span class="rem">//</summary> [WebService (namespa CE = <span class="str">"http://tempuri.org/")] [webservicebinding (conformsto = wsiprofiles.basicprofile1_1)] [ System.ComponentModel.ToolboxItem (<span class="kwrd">false)] <span class="rem">//to allow this Web Service to is called from script, using asp. AJA X, Uncomment the following line. <strong><span style="color: #ff0000;">[System.Web.Script.Services.ScriptService]</span></strong> <span class="kwrd">public <span class="kwrd">class Hellowebservice: System.Web.Services.WebService {[WebMethod] <span class="kwrd">Public <span class="kwrd">string HelloWorld () { <span class="kwrd">return <span class="kwrd">string. Format (<span class="str">"hello,world--{0}", datetime.now);</span> </span> </span> </span> </span> </span> </span> </span> </span> </span> </span> </span> }}} </span></span></span></span></span></pre><p><p></p></p><style><style><!--.csharpcode, .csharpcode pre{font-size: small;color: black;font-family: consolas, "Courier New", courier, monospace;background-color: #ffffff;/*white-space: pre;*/}.csharpcode pre { margin: 0em; }.csharpcode .rem { color: #008000; }.csharpcode .kwrd { color: #0000ff; }.csharpcode .str { color: #006080; }.csharpcode .op { color: #0000c0; }.csharpcode .preproc { color: #cc6633; }.csharpcode .asp { background-color: #ffff00; }.csharpcode .html { color: #800000; }.csharpcode .attr { color: #ff0000; }.csharpcode .alt {background-color: #f4f4f4;width: 100%;margin: 0em;}.csharpcode .lnum { color: #606060; }--></style></style><p><p></p></p><p><p>Above is the definition of a simple XML Web service. It is important to note that if you want to support Ajax access, You must add ScriptService this Attribute.</p></p><p><p>Our calling code is as Follows:</p></p><pre class="csharpcode"><pre class="csharpcode"> <span class="rem">XML Web Service only supports post, which cannot be cached in the browser, but can be combined with server-side caching to reduce the number of background code executions to improve performance by $ (<span class="str">"#btCallXMLWebService"). Click ( <span class="kwrd">function () { $.ajax ({ <span class="str">"<strong><span style="color: #ff0000;">POST</span></strong>", <span class="str">"application/json;utf-8", <span class="str"><span class="kwrd"><span class="str"><span class="kwrd">function ( Result) {alert (result.d);}}); });</span></span></span></span></span></span></span></span></span></pre></pre><p><p></p></p><style><style><!--.csharpcode, .csharpcode pre{font-size: small;color: black;font-family: consolas, "Courier New", courier, monospace;background-color: #ffffff;/*white-space: pre;*/}.csharpcode pre { margin: 0em; }.csharpcode .rem { color: #008000; }.csharpcode .kwrd { color: #0000ff; }.csharpcode .str { color: #006080; }.csharpcode .op { color: #0000c0; }.csharpcode .preproc { color: #cc6633; }.csharpcode .asp { background-color: #ffff00; }.csharpcode .html { color: #800000; }.csharpcode .attr { color: #ff0000; }.csharpcode .alt {background-color: #f4f4f4;width: 100%;margin: 0em;}.csharpcode .lnum { color: #606060; }--></style></style><p><p></p></p><p><p>After running, We click this button multiple times and intercept the following request:</p></p><p><p></p></p><p><p>According to the above is not difficult to see, in fact, each request is re-processed, they are the return status code of 200.</p></p><p><p>This is the processing of the post Ajax request, which is not cached by the Client. Then you might say, can you change the type to get? such as the following</p></p><pre class="csharpcode"><pre class="csharpcode"> $ (<span class="str">"#btCallXMLWebService"). Click (<span class="kwrd">function () { $.ajax ({ <span class="str">"<span style="color: #ff0000;"><strong>GET</strong></span>", <span class="str">"application/ Json;utf-8 ", <span class="str">" Hellowebservice.asmx/helloworld ", <span class="kwrd"><span class="str"><span class="kwrd">function (result) {alert (result.d);});});</span></span></span> </span></span></span></span></span></pre></pre><p><p></p></p><style><style><!--.csharpcode, .csharpcode pre{font-size: small;color: black;font-family: consolas, "Courier New", courier, monospace;background-color: #ffffff;/*white-space: pre;*/}.csharpcode pre { margin: 0em; }.csharpcode .rem { color: #008000; }.csharpcode .kwrd { color: #0000ff; }.csharpcode .str { color: #006080; }.csharpcode .op { color: #0000c0; }.csharpcode .preproc { color: #cc6633; }.csharpcode .asp { background-color: #ffff00; }.csharpcode .html { color: #800000; }.csharpcode .attr { color: #ff0000; }.csharpcode .alt {background-color: #f4f4f4;width: 100%;margin: 0em;}.csharpcode .lnum { color: #606060; }--></style></style><p><p></p></p><p><p>The answer is that for XML Web service or standard WCF services, they do not support requests via get and only support post Requests.</p></p><p><p></p></p><p><p>The server returned an error with a status code of 500 and described the error message in the body, as shown in</p></p><p><p></p></p><p><p>so, for this scenario, do we have any way to optimize it?</p></p><pre class="csharpcode"><span class="kwrd">Using System;<span class="kwrd">Using System.Web.Services;<span class="kwrd">Namespace webapplication4{<span class="rem"><summary><span class="rem">Summary description for Hellowebservice<span class="rem"></summary> [WebService (Namespace =<span class="str"><span class="str"> "http://tempuri.org/")] [webservicebinding (conformsto = wsiprofiles.basicprofile1_1)] [System.ComponentModel.ToolboxItem (<span class="kwrd">false)] <span class="rem">//to allow this Web Service to be Called from script, using asp. AJAX, uncomment the following line. [System.Web.Script.Services.ScriptService] <span class="kwrd">public <span class="kwrd">class hellowebservice: System.Web.Services.WebService {<span class="rem">///<summary> <span class="rem">///the method was cached for 10 seconds, is to cache the results in server Memory. <span class="rem">///</summary> <span class="rem">///<returns></returns> <strong> <span style=" Color: #ff0000; "> [WebMethod (cacheduration=10)] </span> </strong> <span class="kwrd">public <span class="kwrd">string HelloWorld () { Span class= "kwrd" >return <span class="kwrd">string. Format (<span class="str"> "hello,world--{0}", datetime.now);}} </span> </span> </span> </span> </span> </span> </span> </span></span></span></span></span></span></span></span></span></span></span></span></span></pre><p><p></p></p><style><style><!--.csharpcode, .csharpcode pre{font-size: small;color: black;font-family: consolas, "Courier New", courier, monospace;background-color: #ffffff;/*white-space: pre;*/}.csharpcode pre { margin: 0em; }.csharpcode .rem { color: #008000; }.csharpcode .kwrd { color: #0000ff; }.csharpcode .str { color: #006080; }.csharpcode .op { color: #0000c0; }.csharpcode .preproc { color: #cc6633; }.csharpcode .asp { background-color: #ffff00; }.csharpcode .html { color: #800000; }.csharpcode .attr { color: #ff0000; }.csharpcode .alt {background-color: #f4f4f4;width: 100%;margin: 0em;}.csharpcode .lnum { color: #606060; }--></style></style><p><p>After this modification, for the client, there is actually no change, multiple calls, the server needs to process, and then return the status code of 200. But what is the difference? The difference is that the server does not need to run the real code every time, it caches the results in memory and repeats the call within 10 seconds, returning the data in that memory directly. (this can improve the performance of the server and improve Concurrency)</p></p><p><p></p></p><p><p>Note If WCF is the service, the default is not to support caching of operations directly.</p></p><p><p></p></p>How to design a service that supports get<p><p>We learned that by default, both XML Web service and WCF services support AJAX calls that use the Post method only. So is there a way to design a service that supports get?</p></p> <ol> <ol> <li>The XML Web service does not support get</li> <li>WCF services can support get through a special webhttpbinding. This article will discuss this Approach.</li> </ol> </ol> <blockquote> <blockquote> <p>"remarks" WCF has a variety of applicable scenarios, I have written two articles before, interested friends can refer to</p> </blockquote> </blockquote><em><em>different application scenarios of WCF technology and its implementation analysis</em></em><em><em>different application scenarios and implementation analysis of WCF technology (cont.)</em></em> <blockquote> <blockquote> <p>3. The Web API feature can be supported in asp. net mvc, and can be called by a get method. This practice, this article does not do discussion, interested friends can refer to Http://www.asp.net/web-api</p> </blockquote> </blockquote><p><p></p></p><p><p>Let's look at an example. Support for a special operation in WCF is the WebGet</p></p><pre class="csharpcode"><pre class="csharpcode"><span class="kwrd">using system;<span class="kwrd"> Using system.servicemodel; <span class="kwrd">using System.ServiceModel.Activation; <span class="kwrd">using System.ServiceModel.Web; <span class="kwrd">namespace webapplication4{[servicecontract (namespace = <span class="str" )] <strong> <span style="color: #ff0000;"> [aspnetcompatibilityrequirements (requirementsmode = aspnetcompatibilityrequirementsmode.allowed)] </span> <span class="kwrd">public <span class="kwrd">class hellowcfservice {<strong> <span style="color: #ff0000;"> [webget (responseformat = webmessageformat.json)] </span> </strong> <span class="kwrd">public <span class="kwrd">string restfulhelloworldwithparameter (<span class="kwrd">string Name {<span class="kwrd">return <span class="kwrd">string. Format (<span class="str"> "hello,{0}--{1}", datetime.now, name);}} </span> </span> </span> </span> </span> </span> </span> </span></span></span></span></span></span></span></pre></pre><p><p></p></p><style><style><!--.csharpcode, .csharpcode pre{font-size: small;color: black;font-family: consolas, "Courier New", courier, monospace;background-color: #ffffff;/*white-space: pre;*/}.csharpcode pre { margin: 0em; }.csharpcode .rem { color: #008000; }.csharpcode .kwrd { color: #0000ff; }.csharpcode .str { color: #006080; }.csharpcode .op { color: #0000c0; }.csharpcode .preproc { color: #cc6633; }.csharpcode .asp { background-color: #ffff00; }.csharpcode .html { color: #800000; }.csharpcode .attr { color: #ff0000; }.csharpcode .alt {background-color: #f4f4f4;width: 100%;margin: 0em;}.csharpcode .lnum { color: #606060; }--></style></style><p><p></p></p><p><p>The Ajax calling code is as follows</p></p><pre class="csharpcode"><pre class="csharpcode"> $ (<span class="str">"#btCallRestfulWCFServicebwithParameter"). Click (<span class="kwrd">function () { <span class="kwrd">var name = $ (<span class="str">"#txtName"). Val (); <span class="rem">//get requests are cached by default (in the same browser, the default is the temporary cache, the browser is deleted when it is Closed) $.getjson (<span class="str"><span class="kwrd">function (data) {alert (data.d);});});</span></span> </span> </span></span></span></span></pre></pre><p><p></p></p><style><style><!--.csharpcode, .csharpcode pre{font-size: small;color: black;font-family: consolas, "Courier New", courier, monospace;background-color: #ffffff;/*white-space: pre;*/}.csharpcode pre { margin: 0em; }.csharpcode .rem { color: #008000; }.csharpcode .kwrd { color: #0000ff; }.csharpcode .str { color: #006080; }.csharpcode .op { color: #0000c0; }.csharpcode .preproc { color: #cc6633; }.csharpcode .asp { background-color: #ffff00; }.csharpcode .html { color: #800000; }.csharpcode .attr { color: #ff0000; }.csharpcode .alt {background-color: #f4f4f4;width: 100%;margin: 0em;}.csharpcode .lnum { color: #606060; }--></style></style><p><p></p></p><p><p>After running, we enter a different name parameter, and call two times, respectively.</p></p><p><p></p></p><p><p>We can see that the first call returns the status code (200), and the second call returns the status code (304), but if the argument is different, the status code (200) is Returned. In Turn.</p></p><p><p>And we can actually find two cached data in the browser Cache.</p></p><p><p></p></p><p><p></p></p><p><p>So for a get request, it is cached by Default. But what if you want to change this behavior, for example if you don't want to do caching at times?</p></p><p><p></p></p>Avoid caching of Get requests<p><p>sometimes, we may want get requests not to be cached, there are several ways to achieve this purpose.</p></p> <ol> <ol> <li>Each time a call is called, a different address is requested (a random number can be added after the original address) such as the Following:</li> </ol> </ol><pre class="csharpcode"><pre class="csharpcode"> $ (<span class="str">"#btCallRestfulWCFServicebwithParameter"). click (function () { var name = $ (<span class="str">"#txtName"). Val (); <span class="rem">//get requests are cached by default (in the same browser, the default is the temporary cache, the browser is deleted when it is Closed) $.getjson (<span class="str">"hellowcfservice.svc/ Restfulhelloworldwithparameter ", {name:name,<strong><span style="color: #ff0000;">version:Math.random ()</span></strong> }, function (data) { alert (data.d); }); });</span></span></span></span></pre></pre><p><p></p></p><style><style><!--.csharpcode, .csharpcode pre{font-size: small;color: black;font-family: consolas, "Courier New", courier, monospace;background-color: #ffffff;/*white-space: pre;*/}.csharpcode pre { margin: 0em; }.csharpcode .rem { color: #008000; }.csharpcode .kwrd { color: #0000ff; }.csharpcode .str { color: #006080; }.csharpcode .op { color: #0000c0; }.csharpcode .preproc { color: #cc6633; }.csharpcode .asp { background-color: #ffff00; }.csharpcode .html { color: #800000; }.csharpcode .attr { color: #ff0000; }.csharpcode .alt {background-color: #f4f4f4;width: 100%;margin: 0em;}.csharpcode .lnum { color: #606060; }--></style></style><p><p></p></p> <ol> <ol> <li>If you are using jquery, you can consider disabling the AJAX cache</li> </ol> </ol><pre class="csharpcode"><pre class="csharpcode"> <span class="kwrd">false});</span></pre></pre><p><p></p></p><style><style><!--.csharpcode, .csharpcode pre{font-size: small;color: black;font-family: consolas, "Courier New", courier, monospace;background-color: #ffffff;/*white-space: pre;*/}.csharpcode pre { margin: 0em; }.csharpcode .rem { color: #008000; }.csharpcode .kwrd { color: #0000ff; }.csharpcode .str { color: #006080; }.csharpcode .op { color: #0000c0; }.csharpcode .preproc { color: #cc6633; }.csharpcode .asp { background-color: #ffff00; }.csharpcode .html { color: #800000; }.csharpcode .attr { color: #ff0000; }.csharpcode .alt {background-color: #f4f4f4;width: 100%;margin: 0em;}.csharpcode .lnum { color: #606060; }--></style></style>Use the new features of HTML5 to reduce unnecessary Ajax calls<p><p>I think a more thorough approach is to consider caching part of the data in the client, and preferably not in a temporary folder, so that it can be used the next time you start up. HTML 5 provides a new feature: local storage, which can be a good solution to this problem if interested friends can refer to the following document</p></p> <ol> <ol> <li>Http://w3school.com.cn/html5/html_5_webstorage.asp</li> </ol> </ol><p><p>Make Ajax calls take advantage of caching features</p></p></span>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.