Best http web page performance practices, best web page performance practices

Source: Internet
Author: User
Tags free cdn

Best http web page performance practices, best web page performance practices

How long will it take for you to open a webpage? I don't want to wait for a second. But in fact, most websites are disappointing in terms of response speed. Now more and more people are building their own websites and blogs. What is the response speed of Your webpage? In this article, we will introduce the best practices for improving web page performance and the corresponding problem solutions, let webmasters or friends who are about to become webmasters know how to test and improve the website response speed, and have more confidence in their own websites.

Best practices

Best practices we reference 35 golden laws from the yahoo front-end performance team. Click here. Next we will summarize the key points of each article in different categories.

Webpage content

  • Reduces the number of http requests
  • Reduce DNS queries
  • Avoid page Jump
  • Cache Ajax
  • Delayed Loading
  • Advance Loading
  • Reduce the number of DOM elements
  • Divide content by domain name
  • Reduce the number of iframe
  • Avoid 404

Server

  • Use CDN
  • Add Expires or Cache-Control header
  • Gzip compressed file
  • Configure ETags
  • Flush output as soon as possible
  • Use GET Ajax requests
  • Avoid empty image src

Cookie

  • Reduce Cookie size
  • Use a non-cookie domain name for the page content

CSS

  • Pin the style sheet to the top
  • Avoid CSS expressions
  • Replace @ import with <link>
  • Avoid using Filters

Javascript

  • Bottom up the script
  • Use external cirpt and CSS files
  • Simplified Javascript and CSS
  • Remove repeated scripts
  • Reduce DOM access
  • Use smart event processing

Image

  • Optimize image optimization CSS Sprite. Do not scale the image in HTML using a small and cacheable favicon. ico

Mobile client

  • Keep a single content smaller than 25KB
  • Packaging Group Creation compliance document
Webpage content reduces the number of http requests

80% of the response time is spent on downloading webpage content (images, stylesheets, javascripts, scripts, flash, etc ).Reduce the number of requestsIs the Key to shortening the response time! You can simplify the page design to reduce the number of requests, but the following tips can be used for a large number of pages.

1. bundling files: There are many ready-made libraries that can help you bundle multiple script files into one file, and bind multiple style sheet files into one file to reduce the number of file downloads. For example, you can use ScriptManager in asp.net and Bundling in asp.net MVC.

2.CSS Sprites: Combine multiple images into one image, and use CSS to control where the image is displayed. Let's look at a familiar Sprites instance.

Douban puts his icons together, and then we can see how he controls

.app-icon-read {    background-position: 0 0;}.app-icon {    background: url("/pics/app/app_icons_50_5.jpg") no-repeat scroll 0 0 transparent;    border-radius: 10px 10px 10px 10px;    box-shadow: 1px 1px 2px #999999;    display: inline-block;    height: 50px;    width: 50px;}

3.Image Maps: You can combine multiple images and control the display and navigation through coordinates. Here is a classic example. A person in the selected image will take you to a different link.

4.Inline images: Embed an image into the webpage text using an encoded string. For example, the display effect of the inline image below is a 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;}

The image display effect is shown in the left figure.

Reduce DNS queries

DNS queries also consume response time. If the content of our webpage comes from different domains (for example, an open advertisement is embedded and external images or scripts are referenced ), it takes some time for the client to parse these domains for the first time. DNS query results are cached in the Local System and browser for a period of time. Therefore, DNS query generally affects the first access response speed. The following is a query request to access the dns of the blog garden homepage after I clear the local dns. There are still a lot to look.

Avoid page Jump

When the client receives a jump reply from the server, the client sends a request again based on the address specified by the location in the server response, for example, the following jump reply.

      HTTP/1.1 301 Moved Permanently      Location: http://example.com/newuri      Content-Type: text/html

When the client encounters such a reply, the user can only wait for the client to send the request again, and some websites may even jump n times until he wants to take you to another place... Of course, the user cannot see any page content at this time, and only the browser progress bar is refreshing.

Cache Ajax

Ajax can help us download webpage content asynchronously. However, even if some webpage content is asynchronous, users are still waiting for the returned results. For example, ajax returns a drop-down list of user contacts. Therefore, we should try to apply the following rules to improve the ajax response speed.

  • Add Expires or Cache-Control headers so that replies can be cached by the client
  • Compress the reply content
  • Reduce dns queries
  • Simplified javascript
  • Avoid redirection
  • Configure Etags
Delayed Loading

We need to know about latency loading.Minimum content set required for initial webpage LoadingWhat is it. The remaining content can be pushed to the delayed loading set.

Javascript is a typical method that can delay loading content. A radical approach is to ensure that the webpage can work normally when there is no Javascript before developing the webpage, and then complete some advanced functions by loading the script with delay.

Advance Loading

In contrast to delayed loading, advance loading aims to load the resources accessed on the next webpage in advance. The following lists the types of advance loading.

Unconditional advance loading: after the current webpage is loaded, download other content immediately. For example, google will download the image sprite that will be used in all results immediately after the page is loaded successfully.

Conditional loading: the content to be loaded is inferred based on user input. The Yahoo example is search.yahoo.com,

Expected loading: This usually occurs when the web page is re-designed. Because users often visit the old web page, the local cache of the old web page content is sufficient, which makes the old web page faster, the new webpage content is not cached. Designers can pre-load some content that may be used in the new webpage in the old webpage content, in this way, new web pages will generate resources that need to be downloaded.

Reduce the number of DOM elements

Too many elements in a webpage impose a heavy burden on Webpage loading and script execution. The loading speed of 500 and 5000 elements varies greatly.

If you want to know how many elements are in your webpage, you can use a simple command in your browser to figure out,

  document.getElementsByTagName('*').length

How much is it? When writing this article, yahoo claims that the home page has only over 700 elements, but it is nearly doubled. At least we have more webpages than Yahoo...

Divide content by domain name

The browser generally limits the number of downloads in the same domain. You can increase the number of parallel download connections for the downloaded content by domain name. However, note that the number of domain names to be downloaded is between 2 and 4, otherwise, dns query is also a problem.

Generally, Website planning places static resources on a website similar to static.example.com and dynamic content on www.example.com. Another advantage is that you can avoid using cookies on static domain names. We will refer to the cookie rules later.

Reduce the number of iframe

When using iframe, pay attention to the advantages and disadvantages of iframe.

Advantages

  • It can be used to load slow content, such as advertisements.
  • Security Sandbox protection. The browser will perform security control on the content in iframe.
  • Scripts can be downloaded in parallel.

Disadvantages

  • Loading time is consumed even if the iframe content is empty.
  • Will block page loading
  • No Semantics
Avoid 404

We are no stranger to 404, which means that no resources are found on the server. We should pay special attention not to mention 404 of the cases on the webpage resources we provide, the client sends a request but the server returns a useless result, wasting time.

What's worse, we need to load an external script on the webpage, and a 404 error is returned, which not only blocks the download of other scripts, but also downloads the content (404) the client will use it as Javascript for parsing.

Servers use CDN

Emphasize the first Golden law again to reduce the download time of webpage content. You can also use CDN to increase the download speed. CDN improves the download speed of customers by deploying servers in different regions. If your website has a lot of static content and users all over the world are visiting it, what do I mean by youtube? CDN is essential. In fact, most Internet giants have their own CDN. Our website can first distribute webpage resources through free CDN providers.

Add Expires or Cache-Control header

This rule is divided into two aspects,

  • For static content, set the static content to never expire, or a long time later. Set Expires in IIS to view Configure the HTTP Expires Response Header (IIS 7 ).
  • Apply appropriate Cache-Control to dynamic content so that the browser can send requests based on the conditions. For details about the caching of asp.net, see asp.net cache feature and asp.net caching best practices.
Gzip compressed file

Gzip can usually reduce the page content by 70%, including scripts, style sheets, images, and other files. Gzip is more efficient than deflate, and mainstream servers have corresponding compression support modules.

IIS has built-in Static Compression and Dynamic Compression modules. For details about how to prepare them, see Enable HTTP Compression of Static Content (IIS 7) and Enable HTTP Compression of Dynamic Content (IIS 7 ).

It is worth noting that the PDF file can be removed from the type to be compressed, because the PDF file itself has been compressed, gzip has little effect on it, and will waste the CPU.

Configure ETags

Although the title is ETags, you need to make some judgments based on the specific situation. First, Etag simply uses a file version ID so that the server can easily determine whether the requested content is updated. If not, the server replies with 304 (not modified) to avoid downloading the entire file.

However, even if the mainstream server does not support cross-server judgment, for example, if you get Etags from one server cluster and then send the Etags to another server, the verification may fail.

If you encounter this problem, you can remove Etag in IIS 7 by using the following method, use URL Rewrite, and 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>

IIS8 provides a simple configuration to directly disable 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 soon as possible

In the webpage background program, we know that there is a method called Response. Flush (). Generally we call it at the end of the program, but note that this method can be called multiple times. The purpose is to send the reply content in the existing cache to the client first, so that the client can "work ".

When will this method be called better? Generally, we can call this operation once before loading more external scripts or style sheets, when the client receives a link about the script or other external resources, it can initiate a parallel request to download the file. The server then sends the subsequent processing results to the client.

Use GET Ajax requests

The browser divides the implementation of XMLHttpRequest POST into two steps: first, header, and then send data. However, GET can use a TCP packet to complete the request. In addition, GET is used to retrieve data from the server in terms of semantics, while POST is used to send data to the server. Therefore, we try to use GET to complete data request using Ajax.

For more information about GET and POST, see here.

Avoid empty image src

Empty image src will still send requests from the browser to the server, which is a waste of time and resources of the server. Especially when your website is visited by many people every day, the damage caused by such blank requests cannot be ignored.

The implementation of the browser is also based on RFC 3986-Uniform Resource Identifiers standard. The empty src is defined as the current page.

So pay attention to whether such code exists in our webpage.

Straight HTML

  

JavaScript

  Var img = new Image ();

Img. src = "";

Reduce Cookie size

Cookies are used for authentication or personalized settings, and their information is contained in the http packet header. We should pay attention to the following points for cookies to improve the request response speed,

  • Remove unnecessary cookies.
  • Minimize the cookie size
  • Pay attention to the domain level set by the cookie. do not affect sub-domain unless necessary.
  • Set an appropriate expiration time. A long expiration time can increase the response speed.

For more information about Cookies in asp.net, see ASP. NET Cookies Overview and Configure Use Cookies Mode for Session State (IIS 7)

Use a non-cookie domain name for the page content

Cookies are unnecessary for the static resources of most websites. We can use different domains to store these static files separately. This not only reduces the cookie size, but also improves the response speed, another advantage is that some proxies refuse to cache content with cookies. If these static resource cookies can be removed, these proxies can be used for caching.

The common domain division method is to place static files in static.example.com and dynamic content in www.example.com.

Some websites also need to apply cookies on second-level domain names, and all subdomains will inherit them. In this case, a special domain name will be purchased to store cookie-free static resources. For example, Yahoo! Yimg.com and ytimg.com of YouTube.

CSS sets the style sheet to the top

Placing the style sheet (css) in the HEAD of a webpage will make the webpageAppearanceThe loading speed is faster, because this allows the browser to gradually load the content of the web page that will be downloaded. This is especially important for webpages with a large number of contents. users do not have to wait on a white screen until they can read the downloaded content first.

If you place the style sheet at the bottom, the browser will refuse to render the Downloaded web page, because most browsers try to avoid re-painting during implementation, and the content in the style sheet is the key information for drawing the web page, sorry for the audience before downloading it.

Avoid CSS expressions

CSS expressions can dynamically set CSS attributes.IE5-IE8Supported,Expressions in other browsers are ignored.. For example, the following expression sets different background colors at different times.

 

The problem with CSS expressions is that they are computed more times than we think, not only when the page is drawn or the size is changed, even when we scroll the screen or move the mouse, we still try to avoid the performance loss caused by improper use.

If you want to achieve similar results, we can do it through a simple script.

Replace @ import with <link>

Avoid using @ import because it is equivalent to placing css at the bottom of the webpage content.

Avoid using Filters

AlphaImageLoad is also supported in IE5.5-IE8. The use of this filter will cause the image to be blocked during download. In addition, using this filter will cause memory usage problems. IE9 is no longer supported.

Javascript sets the script to the bottom

HTTP/1.1 specification suggests that the browser should not have more than two parallel download connections for the same hostname. Therefore, when downloading images from multiple domains, you can increase the number of parallel download connections. However, when the script is being downloaded, even different hostname browsers will not download other resources, because the browser will parse and execute the script after it is downloaded.

Therefore, we can consider the following methods to speed up scripts,

  • Set the script to the bottom so that the content required for web page rendering can be loaded and displayed to the user as soon as possible.
  • Currently, mainstream browsers support the defer keyword. You can specify the script to be executed after the file is loaded.
  • The async keyword is added to HTML5 to Allow Asynchronous execution of scripts.
Use external cirpt and CSS files

By using external Javascript and CSS files, these files can be cached by the browser and reused between different request content.

At the same time, converting Javascript and CSS from inline to external also reduces the size of webpage content.

The deciding factor for using external Javascript and CSS files is the Reuse Rate of these external files. If a user visits different pages of the same page or can reuse Scripts Multiple times while browsing our pages, therefore, the form of external files can bring you great benefits. However, for pages that users normally access only once, such as the microsoft.com homepage, inline javascript and css can provide higher efficiency.

Simplified Javascript and CSS

Streamlining removes spaces and comments in Javascript or CSS,

body {    line-height: 1;}ol, ul {    list-style: none;}blockquote, q {    quotes: none;}

Simplified Version

body{line-height:1}ol,ul{list-style:none}blockquote,q{quotes:none}

Statistics show that the average size of the streamlined files is reduced by 21%, even if Gzip files are applied, it is reduced by 5%.

For example, my website has 5 CSS and 4 Javascirpt. The following are the results after bundling and minify respectively.

Before any processing

After binding Javascript and CSS

After simplified Javascript and CSS

There are a lot of tools to help us streamline the process. For details, 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

A good tool for integration with VS is as follows.

  • YUICompressor-compilation integration, included in NuGet.
  • AjaxMin-compilation and integration
Remove repeated scripts

Repeated scripts not only waste the download time of the browser, but also the parsing and execution time. A unified script management module is generally used to avoid the introduction of repeated scripts. This not only avoids the introduction of repeated scripts, but also takes into account script dependency management and version management.

Reduce DOM access

Accessing DOM elements through Javascript is not as fast as we think, and webpages with many elements are particularly slow. for accessing DOM through Javascript, pay attention

  • Cache accessed Elements
  • Offline updates the node and adds the DOM Tree.
  • Avoid using Javascript to fix layout
Use smart event processing

Here, intelligent event processing requires developers to have a deeper understanding of event processing. They should trigger fewer events in different ways as much as possible. If necessary, they should handle the event as soon as possible.

For example, if all 10 buttons in a div require event handles, we can place the event on the div, capture the event during event bubbling, and then determine the event source.

Image Optimization Image

After the artist completes the website image design, we can optimize the image before uploading it.

  • Check whether the number of image colors in the GIF image is the same as that in the color palette. If you find that only four colors are used in the image, and the color slot of the 256 colors is displayed in the color palette, there is still space for compression. You can use imagemagick to check:
    Identify-verbose image.gif
  • Convert the GIF format to PNG to see if it saves 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 another PNG optimization tool) on all PNG images ). For example:
    Pngcrush image.png-rem alla-reduce-brute result.png
  • Run unzip Tran on all JPEG images. This tool can perform non-destructive operations such as the appearance of the image, and it can also be used to optimize and clear comments and other useless information in the image.
    Unzip tran-copy none-optimize-perfect src.jpg dest.jpg
Optimize CSS Sprite
  • Horizontal Picture Arrangement in Spirite, vertical arrangement will increase the file size;
  • The combination of closer colors in Spirite can reduce the number of colors, ideally less than 256 colors for the PNG8 format;
  • Do not leave a large gap between Spirite images. Although this will not increase the file size, it requires less memory for the user agent to decompress the image into a pixel map. 100x100 is 10 thousand pixels, and 1000x1000 is 1 million pixels.
Do not scale images in HTML

Do not use image scaling to adapt to the page. If you need small images, use them directly.

Use small and cacheable favicon. ico

The website icon file favicon. ico, whether on your server or not, the browser will try to request this icon. So make sure this icon

  • Exist
  • File size as small as possible, preferably less than 1 k
  • Set a long expiration time
The mobile client keeps a single content smaller than 25KB

This limit is because the iphone can only cache less than 25 KB. Note:This is the size after decompression.. Therefore, gzip alone may not be enough. The simplified file tool will be used.

Packaging Group Creation compliance document

Packaging page content into composite text is like an Email with multiple attachments. It allows you to obtain multiple forms in an HTTP request. When using this rule, you must first determine whether the user agent is supported (not supported by the iPhone ).

Contact Us

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

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

A Free Trial That Lets You Build Big!

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

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

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

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