Reprinted from: Millisecond must contend, front page performance Best practices-Microsoft Internet Development Support
Reference: Best practices to speeding up Your Web Site-yahoo Developer
How long do you want to wait to open a webpage? I don't want to wait a second. But the truth is that most Web sites are disappointing in terms of response speed. Now more and more people start to build their own website, blog, how fast is your Web page responsive? In this article, we introduce the best practices to improve the performance of Web pages, and the corresponding problem-solving solutions, so that the webmaster or will become a friend of the webmaster know how to test and improve the response speed of the site, more confidence in their own site.
Profile:
Web content
Reduce the number of HTTP requests by reducing the number of DNS queries avoid page jump caching Ajax lazy load pre-load reduce number of DOM elements reduce number of IFRAME by domain name to avoid 404
Server
Use CDN to add expires or Cache-control headers gzip Compressed transfer file configuration etags early flush output use get AJAX request to avoid empty picture src
Cookies
Reduce cookie Size page content using a cookie-free domain name
CSS
Avoid CSS expressions using <link> instead of @import to avoid using filters with style sheets pinned
Javascript
Base script with external javascirpt and CSS files to streamline JavaScript and CSS de-duplication scripts to reduce DOM access using intelligent event handling
Image
Optimize image optimization CSS Sprite do not scale images in HTML using small and cacheable Favicon.ico
Mobile Client
Keep a single content less than 25KB packaged and organized into a compliant document
Content:
Web content reduces the number of HTTP requests
80% response time is spent on downloading Web content (images, stylesheets, javascripts, scripts, flash, etc.). reduce the number of requests is the key to shorten the response time! You can reduce the number of requests by simplifying the page design, but you can use the following tips for more page content.
1. Bundle files : There are now many libraries available to help you bundle multiple script files into one file, and bundle multiple stylesheet files into one file to reduce the number of file downloads. For example, bundling in scriptmanager,asp.net MVC can be used in ASP.
2. csssprites: It is to put a number of pictures into a picture, and then through the CSS to control where to show exactly where the whole picture.
3. Imagemaps: It is also a combination of many pictures, and then through the coordinates to control the display navigation. Here's a classic example where someone in the picture will take you to a different link.
4. inlineimages: Embed the picture into the text of the page with a coded string. For example, the following inline image is displayed as a checked checkbox.
. sample-inline-png { padding-left:20px; Background:white url (' data:image/png;base64,ivborw0kggoaaaansuheugaaabaaaaaqaqmaaaalpw0iaaaablbmveuaaad///+l2z/ DAAAAM0LEQVR4NGP4/5/H/1+G/58ZDRAZ3D/MCH8YW83NDDENGE4UG9C9ZWZ3GVLMDA/A6P9/AFGGFYJOXZTQAAAAAELFTKSUQMCC ') No-repeat scroll left top;}
Reduce the number of DNS queries
DNS queries also consume response time, and if our page content comes from different domain (such as embedding open ads, referencing external images or scripts), it also takes some time for the client to parse the domain for the first time. DNS query results are cached in the local system and in the browser for a period of time, so DNS queries are generally affected by the speed of first-time access response. Here is my query request to access the Blog Park home page DNS after I emptied the local DNS. Look less to go to a lot of OH.
Avoid page jumps
When the client receives a jump reply from the server, the client again sends the request again based on the address specified in the server reply, such as the following jump reply.
http/1.1 301 Moved Permanently location:http://example.com/newuri content-type:text/html
When the client encounters this kind of response, the user can only wait for the client to send the request again, and some sites will even jump n times, jumping to where he wants to take you ... Of course, at this time the user can not see any page content, only the browser's progress bar has been refreshed.
Caching Ajax
Ajax can help us to asynchronously download the content of the Web page, but some Web page content even if it is asynchronous, the user is still waiting for its return results, such as the return of Ajax is a drop-down list of user contacts. Therefore, we should also pay attention to the use of the following rules to improve the response speed of Ajax.
- Add expires or Cache-control headers so that replies can be cached by the client
- Compress reply content
- Reduce DNS queries
- Thin JavaScript
- Avoid jumps
- Configure Etags
Lazy Loading
Here we discuss the need for lazy loading to know what the minimum content set is required for our web page to initially load . The rest of the content can be pushed into the deferred load collection.
JavaScript is typical for content that can be lazily loaded. A more radical approach is to make sure that the Web page is basically working without JavaScript, and then by delaying loading the script to do some advanced functionality.
Pre-load
In contrast to lazy loading purposes, the pre-loading is to load the resources that are accessed in the next page in advance, and the following are the types that are preloaded
Unconditional Pre-loading: When the current page is loaded, download some other content right away. For example, Google will download an image sprite that will be used in all results immediately after the page has been loaded successfully.
Conditional loading: Infer what needs to be loaded according to the user's input, Yahoo's example is search.yahoo.com,
Expected loading: This typically occurs when the Web page is redesigned, because users frequently visit old web pages, local content caches the old pages quickly, and the new page content is not cached, the designer can pre-load some new pages in the content of the old page may be used in the content, This new Web page will be born with some resources that need to be downloaded.
Reduce the number of DOM elements
Too many elements in the Web page load the Web page and the execution of the script is a heavy burden, the 500 elements and 5,000 elements in the loading speed will be very different.
To find out how many elements are in your Web page, you can work out a simple command in the browser,
document.getElementsByTagName(‘*‘).length
How much is it? Yahoo wrote this article at the time that the home page is only more than 700 elements, but now nearly one times. Our web page at least not more than Yahoo ...
Divide content by domain name
Browser generally to the same domain download connection limit, according to the domain name division download can increase the parallel download connection, but note that the control domain name use between 2-4, or DNS query is also a problem.
General site planning places static resources on a static.example.com-like, dynamic content on www.example.com. There is also a benefit to avoiding the use of cookies on static domain names. We will refer to the cookie in the following rules.
Reduce the number of IFRAME
Use IFRAME to understand the advantages and disadvantages of IFRAME
Advantages
- Can be used to load slower content, such as ads.
- Security sandbox protection. The browser will securely control the content in the IFRAME.
- Scripts can be downloaded in parallel
Disadvantages
- Load time is consumed even if the iframe content is empty
- Prevents the page from loading
- No semantics
Avoid 404
404 We are not unfamiliar, on behalf of the server did not find resources, we have to pay special attention to 404 of the situation do not on the Web resources we provide, the client sends a request but the server returned a useless result, time wasted.
What's worse is that we need to load an external script in our web page and return a 404, which not only blocks other scripts from downloading, but also downloads the content (404) that the client will interpret as JavaScript.
Server uses CDN
Emphasize the first golden law again, reducing the download time of Web content. Increasing the download speed can also be boosted by a CDN (content distribution network). CDN improves the download speed of customers by deploying servers in different regions. If you have a lot of static content on your site, users all over the world are visiting, am I talking about YouTube? That CDN is essential. In fact, most of the internet giants have their own CDN. Our own website can be used to distribute web resources through a free CDN provider.
Add expires or Cache-control headers
This rule is divided into two areas,
- For static content, add expires, set static content to never expire, or after a long time. Set Expires in IIS to see Configure the HTTP Expires Response Header (IIS 7).
- For dynamic content, apply the appropriate Cache-control, allowing the browser to send requests based on conditions. For the caching of ASP. NET, you can see the ASP. NET cache feature and ASP. Caching best Practices.
Gzip Compressed transfer files
Gzip can typically reduce the size of 70% of Web pages, including scripts, stylesheets, pictures, and more. Gzip is more efficient than deflate, and mainstream servers have corresponding compression support modules.
IIS has built-in static compression and dynamic compression modules, how to formulate can refer to enable HTTP Compression of static content (IIS 7) and enable HTTP Compression of the dynamic content (I is 7).
It is important to note that the PDF file can be removed from the type that needs to be compressed, because the PDF file itself is compressed, gzip is less effective, and it wastes CPU.
Configure Etags
Although the title is called the preparation of etags, but here you have to make some judgments according to the specific circumstances. First the etag is simply a file version identifier that allows the server to easily determine if the content of the request has been updated, and if not, to reply to 304 (not modified), thus avoiding downloading the entire file.
But Etags version information even if the mainstream server does not support cross-server judgments, such as if you get etags from one server cluster and then send to another, then the checksum is likely to fail.
If you encounter such a problem, you can remove the ETag in IIS 7 by using the URL Rewrite, and then add the following configuration in Web. config
<rewrite> <outboundRules> <rule name= "Remove ETag" > <match servervariable= " Response_etag "pattern=". + "/> <action type=" Rewrite "value=" "/> </rule> </ Outboundrules></rewrite>
The IIS8 provides a simple formulation to directly close the ETag,
<element name= "Clientcache" > <attribute name= "Cachecontrolmode" type= "enum" defaultvalue= "NoControl" > <enum name= "Nocontrol" value= "0"/> <enum name= "DisableCache" value= "1"/> <enum Name = "Usemaxage" value= "2"/> <enum name= "Useexpires" value= "3"/> </attribute> < Attribute name= "Cachecontrolmaxage" type= "TimeSpan" defaultvalue= "1.00:00:00"/> <attribute name= " HttpExpires "type=" string "/> <attribute name=" Cachecontrolcustom "type=" string "/>
<attribute name= "Setetag" type= "bool" defaultvalue= "false"/>
</element>
Flush output as early as possible
In the Web daemon we know there is a method called Response.Flush (), generally we call it all at the end of the program, but note that this method can be called multiple times. The goal is to send the reply content in the existing cache to the client first, so that the client "has a job".
When would it be better to call this method? In general, we can in the need to load the comparison of multiple external script or style sheet can be called in advance, the client received a link to the script or other external resources can be in parallel to the first request to download, the server then send the subsequent processing results to the client.
Using GET AJAX Requests
The browser divides the XMLHttpRequest post into two steps, first sending the header, and then sending the data. But get can use a TCP message to complete the request. In addition, get semantics is to go to the server to fetch data, and post is to send data to the server, so we use AJAX to request data as far as possible through get to complete.
A detailed comparison of Get and post can be seen here.
Avoid empty pictures of SRC
The empty image src still causes the browser to send requests to the server, which is a waste of time and wastes the resources of the server. Especially if your website is visited by many people every day, the damage caused by such an empty request cannot be ignored.
The browser implementation is also based on the RFC 3986-uniform Resource identifiers Standard, empty SRC is defined as the current page.
So notice if there's such a code in our web page.
Straight HTML
JavaScript
var img = new Image ();
IMG.SRC = "";
Cookie reduction Cookie Size
Cookies are used for authentication or personalization, their information is included in the HTTP header, and for cookies we should pay attention to the following points to improve the response speed of the request,
- Remove unnecessary cookies, which are completely banned if the Web page does not require a cookie
- Minimize the size of cookies
- Note that the cookie is set to the domain level and does not affect the sub-domain if necessary
- Set the appropriate expiration time, and the longer expiration time can increase the response speed.
For cookies in ASP, you can refer to the ASP. Overview and configure use cookies Mode for Session State (IIS 7)
Page content uses a cookie-free domain name
Most of the site's static resources do not have the necessary cookies, we can use different domain to separate these static files, not only to reduce the size of cookies to improve the response speed, there is a good thing is that some proxy refused to cache the content with cookies, If these static resource cookies can be removed, then the cache support for these proxies can be obtained.
The common way to divide domain is to put static files in static.example.com, and dynamic content in www.example.com.
There are also some sites need to apply cookies on the level two domain name, all subdomains will inherit, in this case, usually buy a special domain name to store cookie-free static resources. such as Yahoo! 's Yimg.com,youtube ytimg.com and so on.
CSS pinned style sheets
Putting a style sheet (CSS) in the head of a webpage makes the page load faster, because doing so allows the browser to incrementally load the content of the Web page that has been downloaded. This is especially important for pages that are more content, and users don't have to wait on a white screen to see what they have already downloaded.
If you put the style sheet at the bottom, the browser refuses to render the page that has already been downloaded, because most browsers try to avoid redrawing when they are implemented, and the content in the stylesheet is the key information for drawing the page, so I'm sorry for the audience without downloading it.
Avoid CSS expressions
CSS expressions can be dynamically set CSS properties, supported in IE5-IE8 , and expressions in other browsers will be ignored . For example, the following expression sets different background colors at different times.
The problem with CSS expressions is that it is recalculated more often than we think, not only when the page is drawn or resized, but even when we are scrolling the screen or moving the mouse, so we try to avoid using it to prevent improper use of performance loss.
We can do this with a simple script if we want to achieve a similar effect.
Replace @import with <link>The reason to avoid using @import is simple, because it is equivalent to placing CSS at the bottom of the page content.
Avoid using filtersAlphaimageload is also supported in IE5.5-IE8, the use of this filter will cause the image to block the page drawing when downloading, and the use of this filter will cause memory usage problems. The IE9 is no longer supported.
JavaScript to place the script bottomhttp/1.1 specification recommends that browsers do not have more than two concurrent download connections to the same hostname, so you can increase the number of concurrent download connections when you download pictures from multiple domain. However, when the script is downloaded, the other resources are not downloaded even from different hostname browsers because the browser is parsed and executed sequentially after the script is downloaded.
So for the script to speed up, we can consider the following ways,
- Put the script down so that the content needed to render the page is loaded as soon as it appears to the user.
- The DEFER keyword is now supported in mainstream browsers, and you can specify that the script executes after the document is loaded.
- The Async keyword is added to the HTML5 to allow the script to execute asynchronously.
Using external javascirpt and CSS files
Using external JavaScript and CSS files allows these files to be cached by the browser and reused between different request content.
Turning JavaScript and CSS from inline to external also reduces the size of Web content.
The decision to use external JavaScript and CSS files depends on the reuse rate of these external files, and the external file form can be a great benefit if the user browses to our page and accesses multiple pages of the same page or can reuse the script. But for a page that the user usually accesses only once, such as the Microsoft.com homepage, the inline JavaScript and CSS provide a relatively high level of efficiency.
Streamline JavaScript and CSS
Streamlining is simply removing whitespace and annotations from JavaScript or CSS,
body { line-height:1;} OL, ul { list-style:none;} BLOCKQUOTE, q { quotes:none;}
Streamlined version
Body{line-height:1}ol,ul{list-style:none}blockquote,q{quotes:none}
Statistics show that the reduced file size is decreased by an average of 21%, even if the file used for gzip is reduced by 5%.
For example, there are 5 css,4 javascirpt on my website, the following are the results after bundling and minify respectively.
Without any processing before |
After bundling JavaScript and CSS |
After streamlining JavaScript and CSS |
|
|
|
To help us do a lot of streamlining tools, mainly can refer to the following,
JS Compressors:
- Packer
- Jsmin
- Closure compiler
- Yuicompressor (also does CSS)
- Ajaxmin (also does CSS)
CSS Compressors:
- Csstidy
- Minify
- Yuicompressor (also does JS)
- Ajaxmin (also does JS)
- Csscompressor
The tools that are better with VS integration are as follows.
- Yuicompressor-compile integration, included in NuGet.
- Ajaxmin-Compile integration
Remove Duplicate Script
Duplicate scripts not only waste the browser's download time, but also waste parsing and execution time. It is generally used to avoid introducing duplicate scripts by using a unified script management module, which not only avoids repetitive script introductions, but also allows for scripting dependency management and versioning.
Reduce DOM Access
Accessing DOM elements via JavaScript is not as fast as we think, the pages with many elements are especially slow, and for JavaScript access to the DOM we should note
- Cache elements that have already been accessed
- Offline Update node and add back Dom Tree
- Avoid repairing layout with JavaScript
Using Intelligent event Handling
This means that Intelligent event processing requires developers to have a better understanding of event handling, to trigger events in different ways as little as possible, and to handle events as early as necessary.
For example, if 10 buttons in a div require an event handle, then we can place the event on the Div, capture the event as it is bubbling, and then judge the source of the event.
Picture optimization image
After the artist has completed the image design of the website, we can make the following optimizations before uploading the image.
- Check whether the number of image colors in the GIF picture matches the palette specifications. If you find that only 4 colors are used in the image, and the 256-color color slots are displayed in the palette, then this picture has a compressed space. You can use the ImageMagick check:
Identify-verbose Image.gif
- Try converting the GIF format to PNG format to see if you're saving space. In most cases, it can be compressed. The following simple command can safely convert the GIF format to PNG format:
Convert Image.gif image.png
- Run Pngcrush (or other PNG optimization tools) on all PNG images. For example:
Pngcrush Image.png-rem Alla-reduce-brute Result.png
- Run Jpegtran on all JPEG images. This tool can do lossless actions on the appearance of aliasing in the picture, and it can also be used to optimize and erase annotations and other useless information in the picture.
Jpegtran-copy None-optimize-perfect src.jpg dest.jpg
Optimize CSS Sprite
- Spirite horizontal arrangement of pictures, vertical arrangement will increase the file size;
- Spirite The combination of the color closer together can reduce the number of colors, the ideal condition is less than 256 colors in order to apply the PNG8 format;
- Do not leave a large gap in the middle of the spirite image. While this is unlikely to increase the size of the file, it requires less memory for the user agent to decompress the image into a pixel map. 100x100 's picture is 10,000 pixels, and 1000x1000 is 1 million pixels.
Do not scale a picture in HTML
Do not use the image zoom to adapt to the page, if you need small pictures, directly using the small picture it.
Use small, cacheable favicon.ico
Website icon file Favicon.ico, regardless of whether your server has or not, the browser will try to request this icon. So we're going to make sure this icon
- Exist
- File as small as possible, preferably less than 1k
- Set a long expiration time
Mobile client keeps single content less than 25KB
This limitation is because the iphone, he can only cache less than 25K, note that this is the size after decompression . So simple gzip is not necessarily enough, the thin file tool to use.
Packaging is organized into document-compliant
Wrapping the page content into compound text is like an email with multiple attachments, which enables you to get multiple builds in an HTTP request. When you use this rule, first determine whether the user agent is supported (iphone is not supported).
[Reprint] Front end optimization guide