Home  >  Article  >  Web Front-end  >  A detailed introduction to Yahoo's military regulations

A detailed introduction to Yahoo's military regulations

黄舟
黄舟Original
2017-07-24 13:52:031141browse

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 3f1c4e4b6b16bbbd69b2ee476dc4f83a and c9ccee2e6ea535a969eb3f532ad9fe89 blocks can also be compressed. Even if the gzip module is enabled, compressing first can reduce the size by 5% or more. JavaScript and CSS are increasingly used, so compressing the code will have a good effect.

11.Avoid redirection

Category: Content

Redirect uses 301 and 302 status codes , the following is a HTTP header with a 301 status code:

HTTP/1.1 301 Moved Permanently

Location:

Content-Type: text/html

The browser will automatically jump to Location URL specified by the #domain. All the information needed for redirection is in the HTTP header, and the response body is usually empty. In fact, additional HTTP headers, such as Expires and Cache-Control also represent Redirect. There are other ways to redirect: refreshmeta tag and JavaScript, but if you must do a redirect , it is best to use the standard 3xxHTTP status code, mainly so that the return button can be used normally.

Keep in mind that redirects slow down the user experience, and inserting redirects between the user and the HTML document delays everything on the page , the page cannot be rendered, and the component cannot start downloading until the HTML document is served to the browser.

There is a common redirection that is extremely wasteful of resources, and web developers are generally not aware of this, that isURLWhen there is a trailing slash missing. For example, jumping to will return a 301 response that redirects to (Note the slash at the end). In Apache you can use Alias ​​, mod_rewrite or DirectorySlash directive to cancel unnecessary redirects.

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 Alias ​​ and mod_rewrite , provided both code paths are on the same server. If redirection is used because the domain name changes, you can create a CNAME (create a DNS record pointing to another domain name as an alias) combined with the Alias ​​ or mod_rewrite directive.

12.Remove duplicate scripts

Category: javascript

Pages containing duplicate script files will affect performance, which may not be what you think. In a review of the top bigweb sites in the United States, only 2 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 HTTP requests, executes useless JavaScript code, and affects page performance. .

IE will generate unnecessary HTTP requests, while Firefox Won't. In IE, if a non-cacheable external script is introduced twice by the page, it will generate two HTTP# when the page loads. ##ask. Even if the script is cacheable, it will generate additional HTTP requests when the user reloads the page.

In addition to generating meaningless HTTP requests, evaluating the script multiple times also wastes time. Because redundant JavaScript## will be executed in Firefox and IE regardless of whether the script is cacheable or not. #Code.

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

SCRIPT tag in the HTML page:

21363db31a13cbf9f6dcdf53a4fd77c72cacc6d41bbb37262a98f745aa00fbf0

One option in PHP

is to create a file called

insertScript 's function:

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

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 -->

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 dc6dce4a544fdca2df29d5ac0ea9906b 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 dc6dce4a544fdca2df29d5ac0ea9906b 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. .

d5ba1642137c3f32f4f4493ae923989c Advantages:

Introduce slow third-party content such as logos and Advertisement

Security Sandbox

Parallel Download Script

d5ba1642137c3f32f4f4493ae923989c Disadvantages:

Costly, even a blank iframe

Blocks page loading

Non-semantic

22.Put an end to it404

Category: Content

HTTPThe request is expensive, there is no need to use a HTTP request to get a useless response (such as 404 Not Found), It will only slow down the user experience without any benefit.

Some sites use the helpful 404——“You meanxxx ?" This is beneficial to the user experience, but it also wastes server resources (such as databases, etc.). The worst thing is that the external JavaScript linked to has an error and the result is 404. First, this download will block parallel downloads. Secondly, the browser will try to parse the 404 response body because it is JavaScript code and need to find out what parts of it are available.

23.Give Cookie lose weight

Category: cookie

There are many reasons to use cookie, such as authorization and personalization. HTTPcookieInformation in the header is exchanged between the web server and browser . It is important to keep the cookie as small as possible to minimize the impact on user response time.

For more information, please see the articles of Tenni Theurer and Patty Chi: When the Cookie Crumbles . The relevant empirical principles can be summarized as follows:

Clear unnecessary cookie

Guaranteecookie As small as possible to minimize the impact on user response time

Pay attention to setting the appropriate domain level for cookie so as not to affect other subdomains

Set an appropriate validity period. An earlier validity period or none can be deleted faster cookie and improve user response time

24.Place the component under a domain that does not contain cookie

Category: cookie

When the browser sends a request for a static image, cookie is also sent together , and the server does not need these cookie at all. So they will only cause meaningless network traffic, and you should ensure that requests for static components do not contain cookie. You can create a subdomain and deploy all static components there.

If the domain name is www.example.org , you can deploy the static component to static.example.org . However, if a cookie# has been set at the top-level domain example.org or www.example.org ##, then all requests to static.example.org will contain these cookie. At this time, you can buy a new domain name, deploy all the static components, and keep the new domain name without cookie. Yahoo! is using yimg.com , YouTube is ytimg.com , Amazon is images-amazon.com and so on.

Another advantage of deploying static components under a domain that does not contain cookie is that some proxies may refuse caching Components of cookie. One thing to note: If you don’t know whether you should use example.org or www.example.org as your homepage, you can consider it# The impact of ##cookie. If www is omitted, you can only write cookie to *.example.org , so for performance reasons it is best to use the www subdomain, and write cookie under this subdomain.

25.

Minimize DOMaccess

Category: javascript

Use JavaScript to access DOM elements is very slow, so in order to make the page respond more quickly, you should:

Cache the index of the visited element

FirstUpdate nodes "offline" before adding them to the DOM tree

Avoid using JavaScriptFix layout issues

For more information, please see YUI in the cinemaJulien Lecomte's article: High Performance Ajax Applications

26.Use smart event handlers

Category: javascript

Sometimes it feels like the page is not responsive enough because too many frequently executed event handlers have been added to the DOM On different elements of the tree, this is why event delegation is recommended. If there are 10 buttons in a div , it should only be given to the div container Add an event handler instead of one for each button. Events can bubble up, so you can capture the event and know which button is the source of the event.

There is no need to wait for the onload event in order to process the DOM tree, usually as long as the target The element can be accessed in the DOM tree without having to wait for all images to be downloaded. Consider using DOMContentLoaded instead of the onload event, but to make it available in all browsers, use YUI Event Tool, it has a onAvailable method.

For more information, please see the article of YUI in the cinemaJulien Lecomte: High Performance Ajax Applications

27.Select2cdf5bf648cf2f33323966d7f58a7f3fDiscard @import

Category: css

A best practice was mentioned earlier: in order to achieve progressive rendering, CSS should be placed at the top.

Use @import in IE and # at the bottom ##2cdf5bf648cf2f33323966d7f58a7f3f The effect is the same, so it is best not to use it.

28.Avoid using filters

Category: css

IE

ProprietaryAlphaImageLoader Filter can be used to repairIE7Problems with translucent PNG images in previous versions. During the image loading process, this filter will block rendering, freeze the browser, increase memory consumption, and is applied to each element, not each image, so there will be a lot of problems.

The best way is to not use AlphaImageLoader at all, and downgrade gracefully to one that has good support in IEPNG8 picture instead. If you must use AlphaImageLoader , you should use underscore hack: _filter to avoid Affects users of IE7 and higher.

29.Optimize pictures

##Category : Pictures

After the designer makes the pictures, he uploads them to through FTP Before the web server, we can do some things.

Check the GIF picture to see if the number of colors corresponding to the palette size is used in the picture, use imagemagick You can simply check:

identify -verbose image.gif

If the 4 color image is used If the 256 color "slot" in the palette, then there is room for improvement

Try to put GIFConvert the image to PNG and see if the size can be reduced. It usually can. Developers were often reluctant to use PNG images due to limited browser support, but this is a thing of the past. The real problem is that PNG images fully support alpha transparency, while GIF images It does not support transparency gradients, so anything GIF can do, PNG can do (except animation). The following simple command will make the PNG image safe to use:

convert image.gif image.png

"We The emphasis is: Give

PNG a chance. ”

##Use

pngcrush (or other PNG. Optimization tool) processes all PNG images, for example: ##pngcrush image.png -rem alla -reduce -brute result .png

Use

jpegtran

to process all JPEG pictures. This tool supports JPEG Lossless operations on images, such as rotation, can also be used to remove comments and other useless information (such as EXIFinformationP.S. digital Photo information, focal length, aperture, etc.): jpegtran -copy none -optimize -perfect src.jpg dest.jpg

30.

Optimize

CSS Sprite

Category

:

Picture

In

Sprite

the horizontal arrangement of the image is generally smaller than the vertical arrangement of the final file

CombinationSprite Similar colors in the picture can be kept low, ideally 256# PNG8Format

is "mobile friendly" and does not leave too big a gap in the Sprite image. Although it does not affect the image file size to a large extent, doing so can save the memory consumed by the user agent when decompressing the image into a pixel map. The picture of 100×100 is 1 million pixels, and ## A picture of #1000×1000 is 100 million pixels.

3

1.Do not use HTMLZoom images

Category: Picture

Don’t use it just because you can set the width and height in HTML Unnecessarily large picture. If needed

1acf00d8da3c1b4d1e485bf03581baac

Then the image itself (mycat.jpg) should be 100x100px instead of shrinking it to 500x500px picture of.

32.Use a small cacheable favicon.icoP.S. Favorite icon)

Category: Picture

favicon.ico

is an image placed in the root directory of the server. It will cause a lot of trouble, because even if you ignore it, the browser will automatically request it, so it is best not to give it a 404 Not Found Response. And as long as it is on the same server, cookie will be sent every time it is requested. In addition, this image will interfere with the download order, such as in IE In , when you request additional components in onload, favicon will be downloaded first.

So in order to mitigate the shortcomings of favicon.ico, you should ensure:

is small enough, it is best to set the appropriate validity period below 1K

HTTP header (if you want to change it later, you cannot Renamed), it is generally safer to set the validity period to a few months later. You can ensure that the change is known to the browser by checking the last modification date of the current favicon.ico.

Imagemagick

Can be used to handle small favorite icons

33.Ensure all components are smaller than25K

Category: Mobile

这个限制是因为iPhone不能缓存大于25K的组件,注意这里指的是 未压缩的 大小。这就是为什么缩减内容本身也很重要,因为单纯的gzip可能不够。

 

更多信息请查看Wayne SheaTenni Theurer的文章: Performance Research, Part 5: iPhone Cacheability Making it Stick

 

34.把组件打包到一个复合文档里

 

分类: 移动

 

把各个组件打包成一个像有附件的电子邮件一样的复合文档里,可以用一个HTTP请求获取多个组件(记住一点:HTTP请求是代价高昂的)。用这种方式的时候,要先检查用户代理是否支持(iPhone就不支持)。

 

35.避免图片src属性为空

 

分类: 服务器

 

Image with empty string src 属性是空字符串的图片很常见,主要以两种形式出现:

 

straight HTML

<img src=””>

JavaScript

var img = new Image();img.src = 
“”
;


 

这两种形式都会引起相同的问题:浏览器会向服务器发送另一个请求。

 

IE 向页面所在目录发起一个请求

SafariChrome 想当前页面本身发送一个请求

Firefox 3及更早版本与SafariChrome处理方式一样,但3.5解决了这个问题 [bug 444931] ,不会再发送请求了

Opera 遇到有空src属性的图片不做任何处理

为什么图片src属性为空不好?

 

意外发送大量的通信量对服务器来说是很伤的,尤其是在每天有几百万访问量页面的时候。

浪费服务器资源去生成一个根本不可能被看到的页面

可能会污染用户数据,如果追踪请求状态,要么通过cookie要么是其它方式,可能会破坏用户数据。即使图片请求并没有返回图片,整个HTTP头部也会被浏览器接受并读取,包括所有的cookie。虽然其余部分会被丢弃,但这可能已经造成破坏了。

The root cause of the problem is the differences in how various browsers handle URI, which is specified in RFC 3986 Uniform Resource Identifiers are clearly defined in the documentation. If URI is an empty string, it will be treated as a relative URI and followed 5.2## Algorithmic processing defined in section #. The actual situation is that Firefox, Safari and Chrome are all based on the documentation. The specifications listed in section 5.4 are used to handle empty strings, but IE does not handle them correctly. It is said that in the old version of the specification document RFC 2396 Uniform Resource Identifiers (replaced by RFC 3986Abandoned), so strictly speaking, the browser's approach to processing relative URI is correct. The problem is that in this case, the empty string is clearly unintentional (P.S. rather than some relative URI).

Section

4.8.2

of HTML5 is about a1f02c36ba31691bcfe87b2722de723b Tagsrc Description of the attribute, stipulating that the browser will no longer send additional requests:

The src attribute must be present, and must contain a valid URL referencing a non-interactive, optionally animated, image resource that is neither paged nor scripted. If the base URI of the element is the same as the document

' s address, then the src attribute's value must not be the empty string.P.S. " The src attribute must exist, and must have a legal URL to reference non-interactive animation or image resources, and cannot be paged or Contains script. If the element's base URI is the same as the document address, the value of the src attribute cannot be an empty string.")

The above is the detailed content of A detailed introduction to Yahoo's military regulations. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn