A detailed introduction to Yahoo's military regulations

黄舟
Release: 2017-07-24 13:52:03
Original
1130 people have browsed it

yahooThe military regulations are divided into a total of 7categoriesa total of 35articles:

1. Try to reduce the number of HTTP requests

##Category: Content

80%

of end user response time is spent on the front end, of which Most of the time is spent downloading various components on the page: images, style sheets, scripts, Flash, etc. Reducing the number of components will inevitably reduce the number of HTTP requests submitted by the page. This is the key to making your page faster.

One way to reduce the number of page components is to simplify the page design. But is there a way to build complex pages while speeding up response times? Well, there is indeed a way to have your cake and eat it too.

Merging files reduces the number of requests by putting all scripts in one file. Of course, you can also merge all CSS. Merging files can be a cumbersome task if the scripts and styles of each page are different, but doing this as part of the site publishing process can indeed improve response times.

CSS Sprites

are the preferred way to reduce the number of image requests. Integrate all the background images into one image, and then use background-image and background of CSS -position attribute to position the part to be displayed.

Image mapping Can merge multiple pictures into a single picture. The total size is the same, but the number of requests is reduced and accelerated. The page loads. Image maps are only useful if the image is continuous on the page, such as a navigation bar. The process of setting coordinates for image map is boring and error-prone, and it is not easy to use image map for navigation, so this method is not recommended.

Inline images (Base64 encoding) use data: URL mode to convert images Embed page. This will increase the size of the HTML file. Putting inline images in the (cached) style sheet is a good idea and successfully avoids the page becoming "heavy". However, current mainstream browsers do not support inline images well.

Reducing the number of HTTP requests for a page is a starting point. This is an important guiding principle to improve the first visit speed of the site. As written in Tenni Theurer’s blogBrowser Cache Usage Exposed! From , 40% to 60%, the cache is empty when visitors visit your site. Therefore, speeding up the first visit of the page is extremely important to improve the user experience.

2.UseCDNContent Delivery Network )

Category: Server

User Physical distance from the server also has an impact on response times. Deploying content on multiple geographically dispersed servers allows users to load pages faster. But how to do it?

###

The first step in achieving geographically distributed content is: Don't try to redesign your web application to accommodate a distributed structure. Depending on the application, changing the structure may include daunting tasks such as synchronizing session state and replicating database transactions across servers (translations may not be accurate). Proposals to shorten the distance between users and content may be delayed or simply impossible to pass because of this difficulty.

Remember the end user response time from 80% to 90% On the download page components: pictures, styles, scripts, Flash, etc. This is the golden rule of performance. It's better to decentralize static content first rather than redesign the application structure from the beginning. This can not only greatly reduce response time, but also make it easier to show CDN's credit.

Content delivery network (CDN) is a group of web# scattered in different geographical locations ##Server is used to send content to users more efficiently. Typically, the server chosen to deliver content is based on a measure of network distance. For example: choose the server with the smallest number of hops (hop) or the fastest response time.

Some Internet company giants have their own CDN, but use a CDN Service providers are more cost-effective, such as Akamai Technologies , EdgeCast , or level3 . For companies and personal websites that are just starting out, the cost of CDN services is very high, but if your user base becomes larger and larger, becoming more and more global, Then it is still necessary to use CDN in exchange for faster response time. In Yahoo!, move static content from the application's web server to CDN( Including the 3rd party mentioned above and Yahoo’s own CDN )Can improve the response time of end users by 20% or even more. Switching to CDN is a fairly simple code change, but it will drastically improve the responsiveness of your site.

3.Add Expires or Cache-Control HTTP

Category: Server

This rule has two aspects:

For static components: never expire by setting a time in the distant future as Expires

Redundant dynamic components: Use the appropriate Cache-Control HTTP header to let the browser make conditional requests

Web design is getting richer, which means there are more scripts, pictures and Flash on the page. New visitors to the site may still have to submit a few HTTP requests, but by using expiration the component becomes cacheable, which avoids unnecessary requests during subsequent browsing sessions. The HTTP request. ValidityHTTP headers are typically used on images, but they should be used on all components, including scripts, styles, and Flash components .

Browsers (and proxies) use caching to reduce the number and size of HTTP requests so that pages can load faster. webThe server uses the validity periodHTTP response header to tell the client how long each component of the page should be cached. Use a time in the distant future as the validity period, telling the browser that this response will be in 2010year4month15 Will not change today.

Expires: Thu, 15 Apr 2010 20:00:00 GMT

If you are using the Apache server , use the ExpiresDefault directive to set the validity period relative to the current date. The following example sets an expiration date of 10 years from the request time:

ExpiresDefault "access plus 10 years"

Remember, if you use a time in the distant future as the validity period, you will have to modify the component's file name in time after the component changes. At Yahoo!, we often do this as part of the build process: embed the version number in the component's filename, for example: yahoo_2.0.6.js

Use a time in the distant future for the validity period HTTP header, which will only affect the page view after the user has visited the site. If it is a new visitor or the browser's cache is cleared, it will not affect the number of HTTP requests. This performance improvement therefore depends on how often users who have cached individual components visit the site. We measured this data at Yahoo! and found that page views (PV) of cached components accounted for 75% to 85%. By using a time in the distant future as the expiration HTTP header, the number of components cached by the browser is increased and does not require Internet on subsequent page views The connection sends even one more byte.

4.GzipComponent

Category : Server

Front-end engineers can find ways to significantly shorten the time it takes to transmit HTTP requests and responses over the network. There is no doubt that the end user's bandwidth speed, network service provider, distance of peer exchange points, etc. are all beyond the control of the development team. But there are other factors that can affect response times. Compression can improve response times by reducing the size of HTTP responses.

Starting from HTTP/1.1, the web client has support for compression The Accept-Encoding HTTP request header.

Accept-Encoding: gzip, deflate

If the web server sees this request header, it will compress the response using one of the methods listed by the client. webThe server notifies the client through the Content-Encoding corresponding header.

Content-Encoding: gzip

Gzip is currently the most common efficient compression method, developed by GNU Project developed and RFC 1952 standardized. The only other compression format you might see is deflate, but it's not very efficient and uncommon.

Gzipping Generally the response can be compressed to around 70%, currently about 90 %'s network transmission through the browser supports gzip. If it is an Apache server, the module to configure gzip depends on the version: Apache 1.3Use mod_gzip while Apache 2.x is the mod_deflate module.

Certain factors in browsers and proxies may cause a mismatch between what the browser expects and the compressed content it receives. Fortunately, these rare encounters are gradually decreasing as older browsers are retired, and the Apache module can automatically add the appropriate VaryResponse header to help you get it done.

The server will decide whether to use gzip compression based on the file type, but this is very limited. Most websites use gzip to compress HTML files. In fact, compressing scripts and style sheets is also a good choice, but many websites miss it. Got this opportunity. In fact, any text content can be compressed, including XML and JSON, while images and PDF No need to compress, because they have already been compressed. Using gzip to compress will not only waste CPU, but may also increase the pressure. The bigger.

Using gzip to compress as much as possible can make the page lose weight. This is also the easiest way to improve the user experience.

5.Put the style sheet at the top

Category: css

When Yahoo! was studying performance, we found that putting the style sheet in the document The HEAD section makes the page appear to load faster. This is because placing the style sheet in head allows the page to render gradually.

Front-end engineers who are concerned about performance want the page to render gradually. In other words, we want the browser to display existing content as quickly as possible, which is particularly important when there is a lot of content on the page or when the user's Internet connection is very slow. The importance of displaying feedback to users (such as progress indicators) has been extensively researched and documented down. In our example, the HTML page is the progress indicator! When the browser gradually loads the page header, navigation bar, top logo, etc., these are treated as feedback by users who are waiting for the page to load, which can improve the overall user experience. .

In many browsers (including IE), put the style sheet in HTMLThe bottom of the document will prevent the page from rendering gradually. These browsers block the rendering process to avoid redrawing page elements due to style changes, leaving the user staring at a blank page.

HTMLThe official document clearly describes that the style sheet should be placed inside the HEAD:"Unlike A, [LINK] may only appear in the HEAD section of a document, although it may appear any number of times." (Unlike a# The ## tag, link tag may only appear in the HEAD section, although it can appear any number of times). Blank screens or unstyled falsh content are not acceptable. The ideal solution is to follow the HTML official documentation and place the style sheet in the HEAD of the HTML document part.

6.Put the script at the bottom

Category : javascript

The script will block parallel downloads, HTTP/1.1The official document recommends the number of components to be downloaded in parallel under each host name of the browser No more than two, if the image comes from multiple hostnames, the number of parallel downloads can be more than two. If the script is downloading, the browser will not start any other download tasks, even under a different hostname.

Sometimes, it’s not easy to move the script to the bottom. For example, if the script is inserted into the page content using document.write , there is no way to move it further down. There may also be scoping issues, which in most cases can be resolved.

A common suggestion is to use a deferred (deferred) script, there is DEFER The script attribute means that it cannot contain document.write, and prompts the browser to tell them they can continue rendering. Unfortunately, Firefox does not support the DEFER attribute. In IE, the script may be deferred, but not as expected. If the script can be deferred, we can move it to the bottom of the page and the page will load faster.

7.Avoid using CSSExpressions

Category: css

Using CSS expressions to dynamically set CSS properties is a powerful and dangerous way. Supported from IE5, but deprecated from IE8. For example, you can use the CSS expression to set the background color to alternate by hour:

In the above code, the expression method can accept a JavaScript expression. CSSThe property will be set to the result of the expression. The expression method will be ignored by other browsers, so it is only useful to find ways to achieve a cross-browser user experience consistent with IE .

The biggest problem with expressions is that they are often re-evaluated, more times than we think. Expressions are re-evaluated not just when the page is rendered and resized, but when the page is scrolled and even when the user moves the mouse around the page. Adding a counter to a CSS expression can track when and how often it is recalculated, and moving the mouse on the page can trigger 10000 multiple recalculations. calculate.

One way to reduce CSS expression re-evaluation is to use a one-time expression, that is, after the expression is evaluated for the first time Just set the style attribute to an explicit value and replace the expression. If you must dynamically set style properties throughout the page's life cycle, you can use event handlers instead of CSS expressions. If you must use CSS expressions, remember that they may be re-evaluated thousands of times, affecting the performance of the entire page.

8. Put JavaScript and CSSPut it outside

Category: javascript, css

A lot of performance The principles are all about how to manage external components, however, before these concerns arise you should ask a more basic question: where should JavaScript and CSS To an external file or directly to the page?

Actually, using external files can make the page faster because JavaScript and CSSThe file will be cached in the browser. HTMLInline JavaScript and CSS are executed on each request to the HTML document will be re-downloaded. Doing so reduces the number of HTTP requests required, but increases the size of the HTML document. On the other hand, if JavaScript and CSS are in external files and have been cached by the browser, then we are successful The HTML document has been greatly reduced, and the number of HTTP requests has not been increased.

The key factor is the relationship between the frequency of external files being cached and the number of page requests. Although this factor is difficult to quantify, it can be measured using a variety of metrics. Caching external files can be a huge benefit if the user has multiple page visits per session, so the same scripts and stylesheets can be reused across multiple pages.

Many sites fall in the middle of the pack in metrics, and for these sites, the best solution is generally to combine JavaScript and CSSDeployed as external file. The only exception is inline mode priority on homepages, such as the homepage of Yahoo! and My Yahoo! . Home pages with fewer visits per session will find that inline JavaScript and CSS result in faster response times for end users. .

For a typical site, the homepage is the beginning of many visits. There are many techniques that can leverage the reduction of HTTP requests. The effect is just like the benefits of using external file caching. One such technique is to use inline JavaScript and CSS on the homepage, but dynamically load external files after the page is loaded. In this way, the external files required for subsequent pages have been placed in the browser's cache.

9.ReduceDNSFind

##Category: Content

The domain name system establishes the host name and IP address The mapping between names is like the mapping between names and numbers in the phone book. When you enter www.yahoo.com in the browser, the browser will contact the DNS resolver to return the server's IPAddress. DNS has a cost, it takes 20 to 120 milliseconds to look it up The IP address given the hostname. The browser cannot download anything from the hostname until the DNS lookup is complete.

DNS

Lookups are cached more efficiently, by the user's ISP (Internet Service Provider) or local The network exists on a special caching server, but can also be cached on individual users' computers. DNSThe information is stored in the operating system’s DNS cache(MicrosoftWindows "DNSClient Service"). Most browsers have their own cache independent of the operating system. As long as the browser retains this record in its own cache, it will not query DNS from the operating system.

IEDefault CacheDNSLookup30 minutes, written in DnsCacheTimeout Registry settings. FirefoxCache1 minutes, which can be set using the network.dnsCacheExpiration configuration item. (Fasterfoxchanged the cache time to 1hoursP.S. FasterfoxYesFF A speed-up plug-in)

If the client’s DNS cache is empty (including browser and operating system), DNSThe number of lookups is equal to the number of different host names on the page, including the pageURL, pictures, script files, style sheets, Flash objects and other host names in components, reducing different host names can reduce DNS lookup.

Reducing the number of different host names also reduces the number of components that can be downloaded in parallel on the page, avoiding DNS lookups and reducing response time. Reducing the number of parallel downloads increases response time. My principle is to disperse the components under 2 to 4 host names, which reduces at the same time DNS A compromise between lookup and allowing high concurrent downloads.

10.CompressionJavaScript and CSS

Category: javascript, css

Compression specifically means removing unnecessary elements from the code characters to reduce size and thus load faster. Code minimization means removing all comments and unnecessary whitespace characters (spaces, newlines and tab). Doing this in JavaScript can improve responsiveness because the file to be downloaded becomes smaller. The two most commonly used JavaScript code compression tools are JSMin and YUI Compressor , YUI compressor can also compress CSS.

Obfuscation is an optional source code optimization measure, which is more complicated than compression, so the obfuscation process is also more likely to produce bug. In a survey of the top ten websites in the United States, compression reduced the size by 21%, while obfuscation reduced the size by 25%. Although obfuscation provides a higher degree of reduction, it is more risky than compression.

In addition to compressing external scripts and styles, inline <script> <span style="font-family: 宋体"> and </span><span style="font-family: Calibri"><style> </span><span style="font-family: 宋体"> blocks can also be compressed. Even if the </span><span style="font-family: Calibri">gzip</span><span style="font-family: 宋体"> module is enabled, compressing first can reduce the size by </span><span style="font-family: Calibri">5%</span><span style="font-family: 宋体"> or more. </span><span style="font-family: Calibri">JavaScript</span><span style="font-family: 宋体"> and </span><span style="font-family: Calibri">CSS</span><span style="font-family: 宋体"> are increasingly used, so compressing the code will have a good effect. </span></p> <p> </p> <p><strong>11.<span style="font-family: 宋体">Avoid redirection</span></strong></p> <p> </p> <p><span style="font-family: 宋体">Category</span>: <span style="font-family: 宋体">Content</span></p> <p> </p> <p><span style="font-family: 宋体">Redirect uses </span>301<span style="font-family: 宋体"> and </span><span style="font-family: Calibri">302</span><span style="font-family: 宋体"> status codes , the following is a </span><span style="font-family: Calibri">HTTP</span><span style="font-family: 宋体"> header with a </span><span style="font-family: Calibri">301</span><span style="font-family: 宋体"> status code: </span></p> <p> </p> <p>HTTP/1.1 301 Moved Permanently</p> <p> Location:</p> <p> Content-Type: text/html</p> <p><span style="font-family: 宋体">The browser will automatically jump to </span> Location <span style="font-family: 宋体"></span><span style="font-family: Calibri">URL</span><span style="font-family: 宋体"> specified by the #domain. All the information needed for redirection is in the </span><span style="font-family: Calibri">HTTP</span><span style="font-family: 宋体"> header, and the response body is usually empty. In fact, additional </span><span style="font-family: Calibri">HTTP</span><span style="font-family: 宋体"> headers, such as </span><span style="font-family: Calibri">Expires </span><span style="font-family: 宋体"> and </span><span style="font-family: Calibri">Cache-Control </span><span style="font-family: 宋体"> also represent Redirect. There are other ways to redirect: </span><span style="font-family: Calibri">refresh</span><span style="font-family: 宋体">meta tag and </span><span style="font-family: Calibri">JavaScript</span><span style="font-family: 宋体">, but if you must do a redirect , it is best to use the standard </span><span style="font-family: Calibri">3xxHTTP</span><span style="font-family: 宋体"> status code, mainly so that the return button can be used normally. </span></p> <p> </p> <p><span style="font-family: 宋体">Keep in mind that redirects slow down the user experience, and inserting redirects between the user and the </span>HTML<span style="font-family: 宋体"> document delays everything on the page , the page cannot be rendered, and the component cannot start downloading until the </span><span style="font-family: Calibri">HTML</span><span style="font-family: 宋体"> document is served to the browser. </span></p> <p> </p> <p><span style="font-family: 宋体">There is a common redirection that is extremely wasteful of resources, and </span>web<span style="font-family: 宋体"> developers are generally not aware of this, that is</span><span style="font-family: Calibri">URL</span><span style="font-family: 宋体">When there is a trailing slash missing. For example, jumping to </span><span style="font-family: Calibri"> </span><span style="font-family: 宋体"> will return a </span><span style="font-family: Calibri">301</span><span style="font-family: 宋体"> response that redirects to </span><span style="font-family: Calibri"> </span><span style="font-family: 宋体"> (Note the slash at the end). In </span><span style="font-family: Calibri">Apache</span><span style="font-family: 宋体"> you can use </span><span style="font-family: Calibri">Alias ​​</span><span style="font-family: 宋体">, </span><span style="font-family: Calibri">mod_rewrite </span><span style="font-family: 宋体"> or </span><span style="font-family: Calibri">DirectorySlash </span><span style="font-family: 宋体"> directive to cancel unnecessary redirects. </span></p> <p> </p> <p><span style="font-family: 宋体">The most common use of redirection is to connect the old site to the new site. It can also connect different parts of the same site and do some processing according to the different situations of the user (browser type, user account type, etc.) . Connecting two websites using redirects is the simplest and requires only a small amount of additional code. Although using redirects at these times reduces development complexity for developers, it reduces user experience. An alternative is to use </span> Alias ​​<span style="font-family: 宋体"> and </span><span style="font-family: Calibri">mod_rewrite </span><span style="font-family: 宋体">, provided both code paths are on the same server. If redirection is used because the domain name changes, you can create a </span><span style="font-family: Calibri">CNAME</span><span style="font-family: 宋体"> (create a </span><span style="font-family: Calibri">DNS</span><span style="font-family: 宋体"> record pointing to another domain name as an alias) combined with the </span><span style="font-family: Calibri">Alias ​​</span><span style="font-family: 宋体"> or </span><span style="font-family: Calibri">mod_rewrite </span><span style="font-family: 宋体"> directive. </span></p> <p> </p> <p><strong>12.<span style="font-family: 宋体">Remove duplicate scripts</span></strong></p> <p> </p> <p><span style="font-family: 宋体">Category</span>: javascript</p> <p> </p> <p><span style="font-family: 宋体"> Pages containing duplicate script files will affect performance, which may not be what you think. In a review of the top </span><span style="font-family: 宋体">big</span><span style="font-family: Calibri">web</span><span style="font-family: 宋体"> sites in the United States, only </span><span style="font-family: Calibri">2</span><span style="font-family: 宋体"> sites were found to contain duplicate scripts . Two main reasons increase the chances of duplicate scripts appearing on a single page: team size and number of scripts. In this case, the duplicate script creates unnecessary </span><span style="font-family: Calibri">HTTP</span><span style="font-family: 宋体"> requests, executes useless </span><span style="font-family: Calibri">JavaScript</span><span style="font-family: 宋体"> code, and affects page performance. . </span></p> <p> </p> <p>IE<span style="font-family: 宋体"> will generate unnecessary </span><span style="font-family: Calibri">HTTP</span><span style="font-family: 宋体"> requests, while </span><span style="font-family: Calibri">Firefox</span> <span style="font-family: 宋体">Won't. In </span><span style="font-family: Calibri">IE</span><span style="font-family: 宋体">, if a non-cacheable external script is introduced twice by the page, it will generate two </span><span style="font-family: Calibri">HTTP</span># when the page loads. ##ask. Even if the script is cacheable, it will generate additional <span style="font-family: 宋体"></span>HTTP<span style="font-family: Calibri"></span> requests when the user reloads the page. <span style="font-family: 宋体"></span></p> <p></p> <p>In addition to generating meaningless <span style="font-family: 宋体">HTTP</span> requests, evaluating the script multiple times also wastes time. Because redundant <span style="font-family: 宋体"></span>JavaScript## will be executed in <span style="font-family: Calibri"></span>Firefox<span style="font-family: 宋体"></span> and <span style="font-family: Calibri"></span>IE<span style="font-family: 宋体"></span> regardless of whether the script is cacheable or not. <span style="font-family: Calibri">#Code. </span><span style="font-family: 宋体"></span> </p> <p></p>One way to avoid accidentally introducing the same script twice is to implement a script management module in the template system. A typical way to introduce a script is to use the <p><span style="font-family: 宋体">SCRIPT</span><span style="font-family: 宋体"> tag in the </span>HTML<span style="font-family: Calibri"> page: </span><span style="font-family: 宋体"></span> </p> <p><script type="text/javascript" src="menu_1.0.17.js?1.1.11"></script>

One option in PHP

is to create a file called

insertScript 's function:

<?php insertScript("menu.js?1.1.11") ?>
Copy after login

In addition to preventing the same script from being introduced multiple times, this function can also solve other script-related problems, such as dependency checking and Add a version number to the script file name to support the

"permanent" expiration HTTP header.

13.

ConfigurationETags

Category

: Server

Entity tags (ETags) are a mechanism used by servers and browsers to determine whether components in the browser cache match components in the origin server ("entities" are components: images, scripts, stylesheets, etc.). Adding ETags provides an entity validation mechanism that is more flexible than last modified date. An ETag is a string that serves as a unique identifier for a specific version of a component. The only formatting constraint is that the string must be enclosed in quotes, and the origin server specifies the component's ETag using the ETag in the corresponding header. :

HTTP/1.1 200 OK

Last-Modified: Tue, 12 Dec 2006 03:03:59 GMT

ETag: "10c24bc-4ab-457e1c1f"

Content-Length: 12195

Then, if the browser must validate a component, it uses If-None-Match Request header to pass ETag back to the origin server. If ETags matches successfully, a 304 status code will be returned, thus reducing 12195 byte response body.

GET /i/yahoo.gif HTTP/1.1

Host: us.yimg.com

If-Modified-Since: Tue, 12 Dec 2006 03:03:59 GMT

If-None-Match: "10c24bc-4ab-457e1c1f"

HTTP/1.1 304 Not Modified

ETagsThe problem is that they are constructed by a specific server, so if the browser gets the initial component from one server and then wants to validate the same component on another server, ETags It is impossible to match successfully, and using a group of servers to handle requests is very common in web sites. By default, Apache and IIS will embed data in ETag, To greatly reduce the chance of successful validity testing on a multi-server site.

Apache 1.3 and 2.x ETag The format is inode-size-timestamp . Even though a given file may be in the same directory on multiple servers, and the file size, access permissions, timestamps, etc. are all the same, its inode (P.S. inode, index file in UNIX) is also different in different servers.

IIS5.0 and 6.0 also have similar problems. The format of ETags in IIS is Filetimestamp:ChangeNumber , ChangeNumber is a counter used to track IIS configuration changes. The ChangeNumber of a site on different IIS servers cannot be the same.

The end result is Apache and IIS generated ETags for the exact same component Cannot be matched across browsers, if ETags do not match, the user will not receive the 304 response designed for small and fast ETags. Instead, they will receive a 200normal response carrying all the data for the component. If the site is deployed on a single server, this problem does not exist at all. But if the site is deployed on multiple servers and you plan to use the default ETags# of Apache or IIS ##Configuration, users will see slow pages, higher server load, greater bandwidth consumption, and the proxy cannot effectively cache page content. Even if the component has a "permanent" Expires HTTP header, when the user clicks to reload or refresh, a conditional GET request will still be issued.

If you don’t want to use the flexible verification model provided by ETags, it is best to put all Etag Remove them all, you can use the Last-Modified HTTP header verification based on the component timestamp, and remove ETag to reduce HTTPThe size of response headers and subsequent requests. Microsoft Support article describes how to remove ETags. In Apache, this can be achieved simply by adding the following code to the Apache configuration file:

FileETag none

14.Make Ajaxcacheable

Category: Content

One of the benefits of Ajax

is that it can provide users with instant feedback. Because it can request information asynchronously from the backend server. However, with Ajax there is no guarantee that the user is waiting for asynchronous JavaScript and XMLThe response return period will not be very boring. In many applications, the user's ability to wait depends on how Ajax is used. For example, in a web-based email client, users will keep searching for Ajax# in order to find email messages that match their search criteria. ##Request attention to return results. It's important to remember that "asynchronous" doesn't mean "immediate".

To improve performance, optimizing these

Ajax responses is critical. The most important way to improve Ajax performance is to make the response cacheable, like adding Expires or # The same as discussed in the ##Cache-Control HTTP header. The following additional rules apply to Ajax:

Gzip

Component

减少DNS查找

压缩JavaScript

避免重定向

配置ETags

我们一起看看例子,一个Web 2.0的电子邮件客户端用了Ajax来下载用户的通讯录,以便实现自动完成功能。如果用户从上一次使用之后再没有修改过她的通讯录,而且Ajax响应是可缓存的,有尚未过期的Expires或者Cache-Control HTTP头,那么之前的通讯录就可以从缓存中读出。必须通知浏览器,应该继续使用之前缓存的通讯录响应,还是去请求一个新的。可以通过给通讯录的Ajax URL里添加一个表明用户通讯录最后修改时间的时间戳来实现,例如 &t=1190241612 。如果通讯录从上一次下载之后再没有被修改过,时间戳不变,通讯录就将从浏览器缓存中直接读出,从而避免一次额外的HTTP往返消耗。如果用户已经修改了通讯录,时间戳也可以确保新的URL不会匹配缓存的响应,浏览器将请求新的通讯录条目。

即使Ajax响应是动态创建的,而且可能只适用于单用户,它们也可以被缓存,而这样会让你的Web 2.0应用更快。

15.尽早清空缓冲区

分类: 服务器

当用户请求一个页面时,服务器需要用大约200500毫秒来组装HTML页面,在这期间,浏览器闲等着数据到达。PHP中有一个 flush() 函数,允许给浏览器发送一部分已经准备完毕的HTML响应,以便浏览器可以在后台准备剩余部分的同时开始获取组件,好处主要体现在很忙的后台或者很“轻”的前端页面上(P.S. 也就是说,响应时耗主要在后台方面时最能体现优势)。

比较理想的清空缓冲区的位置是HEAD后面,因为HTMLHEAD部分通常更容易生成,并且允许引入任何CSSJavaScript文件,这样就可以让浏览器在后台还在处理的时候就开始并行获取组件。

例如:

... <!-- css, js -->
    </head>
    <?php flush(); ?>
    <body>
      ... <!-- content -->
Copy after login

Yahoo!搜索 开创了这项技术,而且真实用户测试研究也证明了使用这种技术的诸多好处。

16.AjaxGET请求

分类: 服务器

Yahoo!The mailbox team discovered that when using XMLHttpRequest , the browser's POST request goes through a two-step The process is implemented: first send the HTTP header, and then send the data. So it is best to use GET request, which only needs to send a TCP message (unless cookieExceptionally many). The maximum length of IEURL is 2K, so if you want to send If the data exceeds 2K, GET cannot be used.

An interesting side effect of the POST request is that no data is actually sent, like the GET request . As described in the HTTP documentation, the GET request is used to retrieve information. So its semantics are just to request data with a GET request, not to send data that needs to be stored to the server.

17.Lazy loading component

Category: Content

You can take a closer look at the page and ask yourself: What is necessary to render the page in the first place? The rest can wait.

JavaScript is ideal for separating before and after the onload event. For example, if you have JavaScript code and a library that supports drag-and-drop and animations, these can wait because drag-and-drop elements occur after the page is initially rendered. Other sections that can be lazy loaded include hidden content (content that appears after an interaction) and collapsed images.

Tools can help you reduce your workload: YUI Image Loader can delay loading of collapsed images, and YUI Get utility is a simple way to introduce JS and CSS. Yahoo!Home page is an example. You can open the network panel of Firebug and take a closer look.

It's best to align performance goals with other web development best practices, such as "progressive enhancement." If the client supports JavaScript, the user experience can be improved, but you must ensure that the page can work properly when JavaScript is not supported. So, once you’re sure your page is working properly, you can enhance it with some lazy-loading scripts to support some fancy effects like drag-and-drop and animations.

18.Preloaded components

Category: Content

Preloading may seem like the opposite of lazy loading, but it actually has a different goal. By preloading components, you can make full use of the browser's idle time to request components (images, styles, and scripts) that will be used in the future. When the user accesses the next page, most of the components are already in the cache, so the page will load faster from the user's perspective.

In actual applications, there are the following types of preloading:

Unconditional Preloading - Start loading as soon as possible, getting some extra components. google.com is a good example of sprite image preloading. This sprite image does not It's not what the google.com homepage needs, but the content on the search results page.

Conditional Preloading - Guess where the user will jump based on user operations and preload accordingly. After typing in the input box of search.yahoo.com , you can see how those additional components are requested to be loaded.

Ahead of Time Preloading - Preload new designs before they are rolled out. We often hear after a redesign: "This new website is good, but it's slower than before." Part of the reason is that the previous pages users visited have old caches, but the new ones are in an empty cache state. experience. This negative impact can be mitigated by preloading some components before a new design is rolled out. The old site can use the browser's idle time to request the images and scripts that the new site needs.

19.Reduce the number of DOM elements

Category: Content

A complex page means downloading more bytes and using JavaScriptAccessDOM will also be slower. For example, when you want to add an event handler, loop through the 500 DOM elements and 5000DOM elements are different.

A large number of DOM elements is a sign - there are some irrelevant tags on the page that need to be cleaned up. Are you using nested tables for layout? Or did you add a bunch of

s just to fix the layout problem? Perhaps better semantic markup should be used.

YUI CSS utilities Very helpful for layout: grids.cssFor the overall layout, fonts.css and reset.css can be used to remove the browser's default format. This is a good opportunity to start cleaning up and thinking about markup, such as only using

when it makes sense semantically, not because it renders a newline.

DOMThe number of elements is easy to test, just enter in the Firebug console:

document.getElementsByTagName('*').length

So how many DOM elements are too many? You can refer to other similar well-tagged pages, such as Yahoo!The home page is a fairly busy page, but there are less than 700 elements (HTML tags).

20.Cross-domain separation components

Category: content

Separate components can maximize parallel downloads, but make sure to only use no more than 2-4 domains because of DNS lookups cost. For example, you can deploy HTML and dynamic content in www.example.org , and separate static components to static1.example.org and static2.example.org .

For more information, please see the articles of Tenni Theurer and Patty Chi: Maximizing Parallel Downloads in the Carpool Lane

21.Use as little as possibleiframe

Category: Content

UseiframeYou can insert a HTML document into a parent document. The important thing is to understand how iframe works and use it efficiently. .