Website acceleration tips

Source: Internet
Author: User
Tags prefetch website performance

One problem that has plagued many website owners for a long time is that the website access speed is always so slow. If you want to purchase independent bandwidth, the budget is not allowed. If you want to purchase CDN acceleration, the price is too high. Is there any cost-effective solution? From the current big environment analysis, we can only solve this problem through technical means.

Google, a well-known search engine manufacturer that has a deep understanding of web development, released a Firefox/firebug plug-in page speed (why Firefox instead of Chrome?) some time ago ?), The plug-in has been open-source. network administrators and web developers use this plug-in to evaluate the performance of web pages and provide useful suggestions for improving the performance. Today, we called on everyone to work together to accelerate the Internet. Google has shared its research results and data and provided a large number of website acceleration tutorials, this article will sort out these tutorials and share them with you.

CSS: Each declaration is used only once.

To make your website faster, the most important one is that the client code sent to the browser should be as small as possible. When optimizing CSS files, an important principle is that each declaration is used only once. In this way, you can strictly use the selector combination.

For example, you can set these two rules

 
 
  1. h1 { color: black; } 
  2. p { color: black;  

Merge into a rule

 
 
  1. h1, p { color: black; }

This example is the simplest, and the actual development process is much more complicated. Based on my personal development experience, each declaration can be used only once to reduce the size of the CSS file by 20%-24%. The following is a complex example:

 
 
  1. h1, h2, h3 { font-weight: normal; } 
  2. a strong { font-weight: normal !important; } 
  3. strong { font-style: italic; font-weight: normal; } 
  4. #nav { font-style: italic; } 
  5. .note { font-style: italic; }

According to the principle that each statement is used only once, it is reduced

 
 
  1. h1, h2, h3, strong { font-weight: normal; } 
  2. a strong { font-weight: normal !important; } 
  3. strong, #nav, .note { font-style: italic; } 

Note! Important declaration can be different.

Note the following points when applying this method:

◆ First, a long selector may invalidate this method. Repeated selector, such as HTML body table tbody tr td p span. example does not reduce the file size. In fact, using only one declaration may mean that the number of selectors increases, or even lead to a larger CSS file. Using a compact selector is more helpful, it can also improve the readability of style sheets.

◆ Second, be careful with CSS rules. When a user agent cannot parse the selector, the declaration must be ignored. In this case, you only need to modify the rules, it can be used multiple times.

◆ Third and most importantly, if you sort the style sheet, this principle will change your order, but this order can be determined by the browser, if you use this method to run a problem, the best solution is to generate an exception and make the statement multiple times when the problem occurs.

Exercise caution when using a declaration only once to maintain the style sheet. You can use an excellent editor to track changes (such as displaying change rows) and insert a declaration as needed, this method needs to be merged into the workflow. In fact, an effective method is to use indent layout, which makes it easy to find repeated declarations.

Use gzip to compress the page

Gzip compression requires the support of the Web server. Without gzip compression, the web server directly sends the HTML page to the browser, the web server that supports gzip will compress the HTML and send it to the browser. The browser that supports gzip will decompress and decode it locally and display it. Gizp compresses repeated strings, tags, spaces, and style definitions in CSS files, JS files, and HTML files. Let's give an example.

The following code does not compress the first 69 bytes and the last 85 bytes.

 
 
  1. < h1>One< /h1> 
  2. < h2>Two< /h2> 
  3. < h3>Three< /h3> 
  4. < h4>Four< /h4> 
  5. < h5>Five< /h5> 

We replace the title label with the DIV label. The source code size is increased by 10 bytes to 79 bytes, but after compression, it is only 66 bytes.

 
 
  1. < div>One< /div> 
  2. < div>Two< /div> 
  3. < div>Three< /div> 
  4. < div>Four< /div> 
  5. < div>Five< /div> 

HTTP Cache

If you correctly set the HTTP cache header, not only the web page loading speed is faster, but the load on the Web server is also reduced, which is a win-win situation.

The cache is the local copy of The resource. Because many resources are not updated frequently, the browser can directly obtain resources from the local machine without going to the server to save the connection time and resource download time, what really plays a key role in using HTTP cache is the HTTP cache header, which specifies the resource validity period and the last modification time.

HTTP has two methods to define the resource validity period: expires and cache-control: Max-age header. The Expires header specifies the resource expiration date, while the max-age specifies how long the resource will be valid after it is downloaded locally. In fact, the final meanings they need to express are consistent. We recommend that you set the validity period of a resource to one month. If the validity period is longer, you can set it to one year. Generally, you only need to set one of the two headers. If both headers are set, the priority of max-age is higher than that of expires. If your resources are updated more frequently than the specified period, you can rename the resource. The common practice is to add a version number to the resource in the URL, of course, this is the HTML page that references the resource and must be modified accordingly.

When the local resources are in a valid state, the browser has two options: one is to download all the resources again, and the other is to download only the changed resources. In order to allow the browser to download only the changed resources, we need to add conditions in the GET request. The HTTP Protocol gives us two options: Last-modified and etag header.

The last-modified header refers to the last modification time of the resource. The etag header is the unique identification number of different versions of each resource. We recommend that you use the last-modified header, because if the date is early enough, the browser can skip requests to all resources. The following are two test pages.

Disable expires

Enable expires

When loading the page for the second time, you can click the link again or press enter again in the address bar. If you click Refresh, if the resource is still in the cache, the browser is forced to re-use the conditional GET request to obtain the resource.

To better understand this complete process, you can use the httpwatch tool to view the HTTP header. If Apache is used, you can refer to the mod_expires module.

 

Use Page speed to improve website performance

Page speed is an open-source Firefox plug-in released by Google. It can evaluate the performance of web pages, provide reasonable optimization suggestions, and reduce resources.

◆ Image Compression

Image files usually contain some additional information, such as JPEG images, including the information of tools used to create images. PNG images can be reduced by using innovative encoding. These conversions are lossless, the compressed and uncompressed images are the same, but the number of bytes occupied is less,

Page speed uses the optimized image function to try to perform lossless compression on all images on the page. If the compression is successful, the compressed version is displayed. To use the lowest image version, in the page speed panel, click the link to the compressed version, save it, and use it to replace the original image.

◆ JavaScript reduction

Removing comments and spaces from large JavaScript files can greatly reduce the file size, but the function is not damaged. Page speed provides the Javascript cutting function. After the cutting is successful, page speed displays a link to the file. If you want to use the file after the cutting, click the link to save the file, then, rereference the smaller Javascript file on the HTML page.

But there is a problem in doing so, and the mobility of the JavaScript files after the reduction is reduced. If you often update the file, we recommend that you use another command line tool jsmin.

◆ Remove unnecessary CSS

Removing unused rules for CSS files will help reduce the size of CSS files, because browsers often download CSS files to the local place when Browsing Web pages, in this way, the amount of information sent to the browser can be reduced to accelerate the page response speed. However, it is worth noting that some external CSS files are referenced by multiple web pages, be especially careful when removing.

Page speed provides the function of removing different CSS, which tells you that those CSS rules are not used.

In addition to the three features mentioned above, page speed has more features to be explored.

Reduce browser reflow

Reflow is a general term for the browser to re-render a document or a part of the document. It recalculates the location and geometric size of the document element, because reflow is a user interception operation in the browser, this helps developers understand how to improve reflow time and the impact of different document attributes (DOM depth, CSS rule efficiency, and style changes) on reflow time. Sometimes a reflow element may need all the elements in the Reflow document and all the elements that follow it.

Many user behaviors and DHTML changes can trigger reflow, for example, changing the window size, using JavaScript Functions that contain computational styles, adding or removing elements from the Dom, and changing the category of an element triggers reflow, it is worth noting that some actions may lead to more reflow time than you think. Let's look at a picture.


Figure-1 Comparison of reflow time in mainstream browsers

It can be seen that not any style changes in Javascript will trigger reflow. The higher the browser version, the better the Reflow time.

At Google, we conducted a lot of tests on our pages. In the end, we thought that the Reflow time was the most important factor to consider when adding UI elements to the pages. Below are the methods we have organized to help reduce the Reflow time:

◆ Reduce unnecessary Dom depth. Changes to any layer on the DOM tree will affect all layers of the DOM tree. Of course, this will take a lot of time in reflow.

◆ Narrow down CSS rules and remove unnecessary CSS rules.

◆ If you use more complex demo changes, such as animations, you 'd better use absolute positions or fix the positions.

◆ Avoid unnecessary complex CSS selectors, especially derivative selectors. It requires more CPU time to process selector matching.

 

Optimize JavaScript code

Client code can make your application more dynamic, but this Code may make the browser more inefficient and the performance of different clients is not the same. Here we will discuss several tips for optimizing JavaScript.

◆ String usage

In IE6 and IE7, the main problem caused by string cascade is the garbage collection performance. Although these problems have been solved in IE8, however, if most of your users are still using IE or IE7, you must pay special attention to this issue. Let's look at an example first:

 
 
  1. var veryLongMessage = 
  2. 'This is a long string that due to our strict line length limit of' + 
  3. maxCharsPerLine + 
  4. ' characters per line must be wrapped. ' + 
  5. percentWhoDislike + 
  6. '% of engineers dislike this rule. The line length limit is for ' + 
  7. ' style purposes, but we don't want it to have a performance impact.' + 
  8. ' So the question is how should we do the wrapping?';

◆ Replace cascade with connection:

 
 
  1. var veryLongMessage = 
  2. ['This is a long string that due to our strict line length limit of', 
  3. maxCharsPerLine, 
  4. ' characters per line must be wrapped. ', 
  5. percentWhoDislike, 
  6. '% of engineers dislike this rule. The line length limit is for ', 
  7. ' style purposes, but we don't want it to have a performance impact.', 
  8. ' So the question is how should we do the wrapping?'
  9. ].join();

Similarly, the usage level in the condition statement is also very inefficient. The incorrect method is as follows:

 
 
  1. var fibonacciStr = 'First 20 Fibonacci Numbers 
  2. '; 
  3. for (var i = 0; i <  20; i++) { 
  4. fibonacciStr += i + ' = ' + fibonacci(i) + ' 
  5. '; 
  6. }

The correct method:

 
 
  1. var strBuilder = ['First 20 fibonacci numbers:']; 
  2. for (var i = 0; i <  20; i++) { 
  3.   strBuilder.push(i, ' = ', fibonacci(i)); 
  4. var fibonacciStr = strBuilder.join('');

◆ Define class functions

The following functions are inefficient because each time you construct an instance of Baz. Bar, a new function and closure will be created:

 
 
  1. baz.Bar = function() { 
  2.   // constructor body 
  3.   this.foo = function() { 
  4.   // method body 
  5.   }; 

The correct method is:

 
 
  1. baz.Bar = function() { 
  2.   // constructor body 
  3. }; 
  4.  
  5. baz.Bar.prototype.foo = function() { 
  6.   // method body 
  7. }; 

When using this method, no matter how many instances are constructed by Baz. Bar, only one function is created for foo and no closure is created.

◆ Initialize instance variables

Use the instance variable value type initial value to initialize the instance variable Declaration, such as the value, Boolean value, null value, undefined or string, so that unnecessary initialization code can be run every time the constructor is called. Let's look at an example:

 
 
  1. foo.Bar = function() { 
  2.   this.prop1_ = 4; 
  3.   this.prop2_ = true
  4.   this.prop3_ = []; 
  5.   this.prop4_ = 'blah'; 
  6. }; 

You can use:

 
 
  1. foo.Bar = function() { 
  2.   this.prop3_ = []; 
  3. }; 
  4.  
  5. foo.Bar.prototype.prop1_ = 4; 
  6.  
  7. foo.Bar.prototype.prop2_ = true
  8.  
  9. foo.Bar.prototype.prop4_ = 'blah'; 
  10.  

.

◆ Avoid using

To avoid using with in code, it will affect the performance, because it modifies the range chain, so it takes more time to search for other scopes.

◆ Avoid browser memory leakage

For Web applications, memory leakage is very common and may lead to huge performance problems. Because browser memory usage is increasing, your web applications and other programs will become slower, the most common memory leakage is a circular reference between the JavaScript engine and the DOM implemented by the browser C ++ object, for example, between the JavaScript engine and the IE browser's com infrastructure, and the basic structure of the JavaScript engine and Firefox XPCOM.

 

Optimize Web Images

When optimizing the webpage code, don't forget the static content, including images. After simple optimization, the download size can be greatly reduced, and the website quality will not be reduced.

We have summarized some tips to help you speed up loading Web Images:

◆ Trim unnecessary white space


Figure-2 Trim unnecessary Spaces

If you do need a blank padding, you can use CSS code.

◆ Use the best File Format

You can use professional image processing tools, such as Photoshop, to save them as webpage images. If you change the image color from 256 to 32, the file size will obviously decrease, next let's take a look at the comparison of the size of an image in different file formats.


Figure-3 Example Image

The comparison results of different file formats in the image above are as follows:

◇ JPG, 60 quality-32 K

◇ PNG-8, 256 colors-37 k

◇ GIF, 256 colors-42 K

◇ PNG-24-146 K

Because the 8-bit PNG and GIF formats have relatively good image quality and smaller file sizes, we recommend that you use these two formats on the webpage.

PHP performance skills

Edit 51cto note: the PHP team has published an open letter to refute the following content. Whether or not some of the suggestions are correct remains to be further studied.

The usage of PHP is very large, so it is necessary to talk about it here. The first thing to note is that the website performance is related to the PHP version, the web server environment, and the complexity of the Code.

◆ Upgrade PHP

The first thing to do is to upgrade the PHP version. If you are still using php3 or PhP4, upgrade it now!

◆ Use Cache

The cache mode, such as memcached, can cache database query results or web pages to speed up the response of web servers.

◆ Buffer output

PHP uses the memory buffer to store all the data you are trying to print. This buffer seems to slow your webpage because the user must wait for the buffer to be filled up. Fortunately, you can make some modifications to force PHP to quickly clear the output buffer.

◆ Do not copy variables if there is no reason

Some new PHP users try to clear the code by copying pre-defined variables, but this leads to double memory consumption. Let's look at an example. If a malicious user inserts kb content into the text area, the memory will be 1 MB:

 
 
  1. $description = strip_tags($_POST['description']); 
  2. echo $description; 

In the above example, there is no reason to copy the variable. In fact, it can be simplified to avoid additional memory consumption:

 
 
  1. echo strip_tags($_POST['description']); 

◆ Avoid executing SQL queries in a loop

A common mistake is to use SQL queries in a loop, which may cause multiple database round-trips and reduce the script speed. In the following example, you can modify the loop to construct an SQL query, insert all users at a time:

 
 
  1. foreach ($userList as $user) { 
  2.   $query = 'INSERT INTO users (first_name,last_name) VALUES("' . $user['first_name'] . '", "' . $user['last_name'] . '")'; 
  3.   mysql_query($query); 
  4. }

Changed:

 
 
  1. INSERT INTO users (first_name,last_name) VALUES("John", "Doe") 

Without loops, You can merge them into a database query:

 
 
  1. $userData = []; 
  2. foreach ($userList as $user) { 
  3.   $userData[] = '("' . $user['first_name'] . '", "' . $user['last_name'] . '")'; 
  4. $query = 'INSERT INTO users (first_name,last_name) VALUES' . implode(',', $iserData); 
  5. mysql_query($query);Produces: 
  6. INSERT INTO users (first_name,last_name) VALUES("John", "Doe"),("Jane", "Doe")...

◆ Use single quotes for long strings

PHP allows encapsulation of string variables with single quotes and double quotes at the same time, but there is a difference. When double quotes are used, the PHP engine is told to read the string content and find the variables, and then replace them with their values, for a long string that does not contain any variable, the performance may degrade.

◆ Replace if/else with switch/case

The use of switch/case has better performance and maintainability than the use of IF/else.

 

Prefetch Resources

Prefetch resources are pre-downloaded to the local device before the user requests the resource. When the user requests the resource, the network latency can be greatly reduced or even the network latency can be eliminated.

For interactive websites, the optimization speed is not only to reduce the initial download size, but also to download additional resources during user interaction. The speed of these behaviors depends on the time when these resources are downloaded, downloading resources can speed up your website. When designing prefetch resources, consider the following:

◆ Study user behavior

If your users spend a lot of time on a specific page or behavior, you should optimize it. You can find these pages and behaviors by searching server logs. For Picasa network album, we know that the most common operation is to browse images. This is a very suitable prefetch object.

◆ Measuring the time on which a webpage is expected

When the current page is not displayed, you should not extract data from the new page. For dynamic pages, you need to add JavaScript to each external file on the page to load the processing program. When all these resources are downloaded, it is reasonable to prefetch data for the user's next behavior.

◆ Test with tools

Before officially modifying the code, use a tool such as page speed for measurement to avoid website slowdown caused by too much data extraction at a time.

Appropriate include style and script

Generally, the loading time of a webpage is 80-90% of the time spent waiting on the network. The most effective way is to eliminate serialized download resources.

Combine external JavaScript files

When downloading an external script file, the browser generally waits until it downloads the file and continues the subsequent download. This is completely the opposite of parallel image download.

Example 1: two external script files

Example 2: two external Images

In Example 2, when two images take one second to combine, the download is completed in just one second. In example 1, it takes two seconds to complete the download when the two steps are combined. This is two different parallel and serial downloads. Therefore, if you have multiple external script files, you 'd better merge them into one file.

Contains additional CSS files before external JavaScript files

Because the script files will prevent subsequent downloads, those that are already being downloaded will continue to be downloaded.

Example 3: scripts before CSS

Example 4: CSS before the script

In Example 3, the script will cause browser congestion before the CSS file. It takes 2 seconds, but you only need to move the CSS file to the beginning of the script for parallel execution of the download process, example 4. Therefore, if you have both external CSS files and external script files, remember to put the CSS file in front of the script file.

Does not include inline JavaScript between external CSS and other resources

When using the inline script tag, even if it does not download anything, it will also hinder subsequent downloads.

Example 5: CSS inline scripts

Example 6: inline scripts before CSS

In Example 5, the inline script block is located between the style and script, and is serialized during download. in Example 6, move it to the front of the style and restore it to the parallel download mode again. Therefore, if you have an external CSS file, do not insert an inline script tag between your CSS file and the next downloaded resource.

 

Reduce the file size of HTML documents

The best way to reduce the loading time of websites is to reduce the size of HTML files. There are many ways to implement this. First, let's look at which HTML labels can be reduced.

◆ HTML 4

According to the HTML 4 DTD standard, many tags can be omitted, and the following tags in italic can be omitted:

</Area>

</Base>

 

<Body>

 

</Body>

</BR>

</COL>

 

</Colgroup>

</DD>

</DT>

<Head>

</Head>

</Hr>

 

<HTML>

 

</Html>

</Img>

</Input>

 

</LI>

 

</Link>

</Meta>

 

</Option>

 

</P>

</Param>

 

<Tbody>

 

</Tbody>

</TD>

</Tfoot>

</Th>

</Thead>

</Tr>

For example, if you have a list item marked as <li> list item </LI>, You can omit it as <li> list item, </P> is generally used to mark the end of a paragraph, but <p> my paragraph can also be used. This omitted syntax is valid for HTML, body, and head, they are not required in HTML. After such an omission, the entire HTML file size may be reduced by 5-20%.

◆ HTML 5

Although HTML 5 is still under development, it provides you with more options to reduce the file size. For example. HTML 5 allows you to set the document type as follows:

 
 
  1. < !DOCTYPE html> 

Relative

 
 
  1. < !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 

You will notice that the HTML 5 DTD is shorter. When you specify the document encoding, HTML 5 is easier to use and lighter, <meta charset = "UTF-8"> and <meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8"> indicate the same meaning, the browser also knows to process HTML.

In HTML 5, it is worth mentioning that the type attribute associated with the MIME type can be omitted, these attributes, such as type = "text/CSS" or type = "text/JavaScript", describe the content type, you can use <SCRIPT> instead of <SCRIPT type = "text/JavaScript"> and <style> instead of <style type = "text/CSS">.

If you use these methods together, the file size will be reduced by 10-20%. Go to Google's privacy page and use these methods.

Ui message and feeling wait time

For many users, the speed is not equal to the performance. The speed of a website may be affected by their overall experience, including whether they can effectively obtain the desired content, and how the system responds.

When designing your website, consider what the purpose of the user's access to the site is. The faster (the easier) The user can access the website, the better. If the user encounters many difficulties in obtaining content, after the task is completed, they will definitely leave your site immediately and may no longer want to come back.

In fact, to make users feel comfortable using the website, you have a lot to do. Here we only discuss three topics.

1. Is the website design simple enough that even the users who use the website for the first time can find what they want. Out of the box. You can spend 10 days to consider how to optimize the interface process. This saves a lot of time and value for 0.1 million users.

2. Will a message interrupt or add user work steps?

3. What should users do while they are waiting? For example, to display the progress bar, be sure not to design the progress bar too large. We recommend that you use "Uploading ...... "," loading ....... and so on.

Summary

This article lists 12 types of website acceleration methods. In actual work, you can use them flexibly according to your actual situation. After you have mastered these methods, you may be able to bypass the similar methods, this has led you to pursue deeper acceleration methods.

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.