Web Performance optimization

Source: Internet
Author: User
Tags script tag browser cache

The front end is huge, including HTML, CSS, Javascript, Image, Flash, and a variety of resources. Front-end optimization is complex, and there are different ways to do it for every resource. So what is the purpose of front-end optimization?
1. From the user's perspective, optimization allows the page to load faster, respond more quickly to the user's actions, and provide a more user-friendly experience.
2. From a service provider perspective, optimization can reduce the number of page requests, or reduce the bandwidth of requests, can save considerable resources.
In short, proper optimization not only improves the user experience of the site, but also saves considerable resource utilization.
There are many ways to optimize the front-end, according to the granularity can be divided into two categories, the first category is page-level optimization, such as the number of HTTP requests, the non-blocking loading of scripts, the location of the inline script optimization, etc. the second class is code-level optimizations, such as DOM manipulation optimizations in JavaScript, CSS selector optimization, Image optimization and HTML structure optimization and so on. In addition, according to the purpose of improving the input-output ratio, the various optimization strategies mentioned in this paper are roughly arranged in the order of input-output ratio from large to small.
First, page-level optimization
1. Reduce the number of HTTP requests
This strategy is basically known to all front-end people and is the most important and effective. All said to reduce the HTTP request, the request is more than what will happen? First, each request is cost-inclusive, including both the time cost and the resource cost. A complete request requires a "lengthy" and complex process of DNS addressing, establishing a connection with the server, sending data, waiting for the server to respond, and receiving data. The time cost is that the user needs to see or "feel" to the resource that must be waiting for the process to end, and the resource needs to take up the bandwidth because each request carries data. In addition, because the browser requests the number of concurrent requests there is an upper limit (see here), so the number of requests after the browser needs a batch of requests, it will increase the user's waiting time, will cause the user to slow the site such an impression, even if the user can see the first screen of resources have been requested, But the browser's progress bar will always be there.
The main ways to reduce the number of HTTP requests include:
(1). Simplify the page from the design implementation level
If your page is as simple as the homepage of Baidu, then the following rules are largely unnecessary. Keep the page concise and reduce the use of resources most directly. If this is not the case, your page needs a gorgeous skin, then continue reading the content below.
(2). Set the HTTP cache appropriately
The power of the cache is powerful, and the appropriate cache settings can greatly reduce the HTTP request. To have AH home for example, when the browser does not cache when the visit will be issued 78 requests, a total of more than 600 K data (1.1), and when the second access is the browser is cached after access to only 10 requests, a total of more than 20 K data (1.2). (It should be explained here, if the direct F5 refresh the page, the effect is not the same, in this case the number of requests is the same, but the cache resource of the request server is a 304 response, only the header does not have the body, can save bandwidth)
What is the reasonable setting? The principle is simple, the more cache the better, the longer the cache can be better. For example, a picture resource that rarely changes can set a long expiration header directly through the expires in the HTTP header, and a resource that is infrequently changed and potentially variable can use last-modifed for request validation. As much as possible, allow resources to stay in the cache longer. The specific settings and principles of the HTTP cache are no longer detailed here and are interesting to refer to the following articles:
Description of the cache policy in the HTTP1.1 protocol
Fiddler An introduction to caching in HTTP performance
(3). Resource Merging and compression
If possible, combine external scripts, styles, and more than one. In addition, CSS, Javascript, Image can be compressed with the corresponding tools, compression often can save a lot of space.
(4). CSS Sprites
Another good way to reduce the number of requests is to merge CSS images.
(5). Inline Images
Embedding a picture into a page or CSS using Data:url scheme is a good idea if you don't take into account resource management issues. If the page is embedded, the volume of the page is increased, and the browser cache is not available. Using images in CSS is a bit more desirable.
(6). Lazy Load Images (I still don't know about this piece of content)
This strategy does not necessarily reduce the number of HTTP requests, but it can reduce the number of HTTP requests under certain conditions or when the page has just been loaded. For pictures, you can load only the first screen when the page is loaded, and then load the subsequent pictures when the user continues scrolling back. In this way, if the user is only interested in the content of the first screen, then the remaining picture requests are saved. Oh, yes. Home has been the practice is to load the first screen after the picture address cached in the TEXTAREA tag, the user to scroll down the screen when the "lazy" loading.

2. Base the external script (loading the script content after the page information content is loaded)
As mentioned earlier, the browser is capable of concurrent requests, which makes it possible to load resources more quickly, while the outer chain script blocks other resources while it is loading, for example, before the script is loaded, the pictures, styles, and other scripts behind it are blocked until the script is loaded. If you place the script in the pre-comparison position, it will affect the loading speed of the entire page and affect the user experience. There are many ways to solve this problem, here is a more detailed introduction (here is the translation and a more detailed example), and the simplest way to rely on is to move the script as far as possible, reducing the impact on concurrent downloads.
3. Execute the inline script asynchronously (in fact, the same principle as above, to ensure that the script is loaded after the page content.) )
The impact of the inline script on performance is much more than the external script. Home, like an external script, the inline script blocks concurrent requests as it executes, and, in addition, because the browser is single-threaded in page processing, the rendering of the page is deferred when the inline script executes before the page is rendered. In short, when the inline script executes, the page is in a blank state. Given the above two reasons, it is recommended to asynchronously execute a long-executing inline script in many ways, such as using the Defer property of the script element (there are compatibility issues and other issues, such as the inability to use document.write), Using settimeout, in addition, the mechanism of introducing WEB workers in HTML5 can solve such problems.

4. Lazy load Javascript (loaded only when it needs to be loaded, in general, does not load information content.) )
With the popularity of JavaScript frameworks, more and more sites also use the framework. However, a framework often includes a number of feature implementations, which are not required for every page, and can be a waste of resources if you download unwanted scripts-wasting bandwidth and wasting time executing. There are probably two ways to do this, one is to tailor a dedicated mini version to a page that is particularly large, and the other is Lazy Load. Yui used the second way, in Yui's implementation, initially only loaded core modules, other modules can wait until the need to use the time before loading.

5. Place the CSS in the head
If you put CSS in other places such as body, then the browser may have not been downloaded and parsed into the CSS has already started to render the page, which causes the page to jump from a non-CSS state to the CSS state, the user experience is worse. In addition, some browsers will not start rendering the page until the CSS is downloaded, which will cause the browser to postpone rendering time if the CSS is placed in the lower position.
6. Asynchronous request Callback (is to extract some behavior styles, slowly loading the content of the information)
In some pages there may be a need to use the script tag to request data asynchronously. Similar:
Javascript:

function Mycallback (info) {
Do something here
}
Html:

Contents of CB return:
Mycallback (' Hello world! ');
Such a way as above directly on the page to write <script> on the performance of the page is also affected, that is, the load on the page to increase the first time, delayed the domloaded and Window.onload event trigger time. If time-sensitive allows, consider loading when the domloaded event is triggered, or use settimeout mode to flexibly control the timing of the load.
7. Reduce unnecessary HTTP jumps
For HTTP links that are accessed as directories, many people will ignore whether or not the link ends with '/', and if your server treats it differently, you need to be aware that it is likely to hide 301 jumps and add extra requests. See specifically, where the first link is accessed with no '/' end, so the server has a jump.
8. Avoid duplication of resource requests
This situation is mainly due to negligence or the page is composed of multiple modules, and then each module requested the same resources, will lead to duplicate requests for resources

Second, code-level optimization
1. Javascript
(1). DOM
Dom operations should be the most performance-intensive of the scripts, such as adding, modifying, deleting DOM elements, or manipulating DOM collections. If the script contains a large number of DOM operations, you need to be aware of the following points:
A. html Collection (HTML collector, returns an array of content information)
In the script, Document.images, Document.forms, getElementsByTagName () return a collection of htmlcollection types, which are used mostly as arrays when used normally, as it has The Length property, or you can use an index to access each element. However, the performance of the access is much worse than the array, because this collection is not a static result, it represents only a specific query, each access to the collection will be re-executed this query to update the query results. The so-called "Access Collection" includes reading the length property of the collection, accessing the elements in the collection.
Therefore, when you need to traverse the HTML collection, try to convert it to an array and then access it to improve performance. Even if you do not convert to an array, you should access it as little as possible, for example, when traversing, you can save the length property, the member to the local variable, and then use the local variable.
B. Reflow & Repaint
In addition to the above point, DOM operations also need to consider the browser's reflow and repaint, as these are resource-intensive, specific to participate in the following articles:
How to reduce browser repaint and reflow?
Understanding Internet Explorer Rendering Behaviour
Notes on HTML Reflow

(2). Caution With
With (obj) {p = 1}; The behavior of the code block is actually to modify the execution environment in the code block, placing obj at the forefront of its scope chain, and accessing the non-local variable in the with code block is the first lookup from obj, and if it is not followed up by the scope chain, then using with equals increases the scope chain length. Each lookup scope chain is time consuming, and an excessive scope chain causes the lookup performance to degrade.
Therefore, unless you are sure to access only the properties in obj in the with code, use with, instead, the properties that you need to access by using the local variable cache.
(3). Avoid using eval and Function
Each time the Eval or function constructor acts on the source code of a string representation, the scripting engine needs to convert the source to executable code. This is a resource-intensive operation-usually more than 100 times times slower than a simple function call.
The Eval function is particularly inefficient, because the content in the string passed to eval is not known beforehand, and Eval interprets the code to be processed in its context, meaning that the compiler cannot optimize the context, so only the browser can interpret the code at run time. This has a significant impact on performance.
The function constructor is slightly better than eval because using this code does not affect the surrounding code, but it is still slow.
In addition, using eval and function is also detrimental to the JavaScript compression tool to perform compression.
(4). Reduce the scope chain lookup (this aspect of the design to some content related issues)
The previous article addressed the scope chain lookup problem, which is especially important in loops. If you need to access a variable in a non-scoped scope in a loop, cache the variable with a local variable before traversing, and then rewrite that variable after the traversal, which is especially important for global variables, because the global variable is at the top of the scope chain and is accessed most often.
Low-efficiency notation:
Global variables
var globalvar = 1;
function Mycallback (info) {
for (var i = 100000; i--;) {
Each visit to Globalvar needs to find the top of the scope chain, which needs to be accessed 100,000 times in this case
Globalvar + = i;
}
}
More efficient notation:
Global variables
var globalvar = 1;
function Mycallback (info) {
Local Variables Cache global variables
var localVar = Globalvar;
for (var i = 100000; i--;) {
Accessing local variables is the fastest
LocalVar + = i;
}
In this case, you only need to access the global variables 2 times
In the function, you only need to assign the value of the content in the Globalvar to Localvar Jung-gu
Globalvar = LocalVar;
}
In addition, to reduce the scope chain lookup should also reduce the use of closures.
(5). Data access
Data access in JavaScript includes direct quantities (strings, regular expressions), variables, object properties, and arrays, where access to direct and local variables is fastest, and access to object properties and arrays requires greater overhead. It is recommended that you put data in local variables when the following conditions occur:
A. Access to any object property more than 1 times
B. Number of accesses to any array member exceeds 1 times
In addition, the object and array depth lookups should be minimized as much as possible.
(6). String concatenation
Using the "+" sign in JavaScript is inefficient because each run will open up new memory and generate a new string variable, and then assign the stitching result to the new variable. The more efficient way to do this is to use the Join method of the array, where the string to be spliced is placed in the array and the Join method is called to get the result. However, the use of arrays also has some overhead, so you can consider this method when you need to stitch more strings.

For a more detailed description of JavaScript optimizations, refer to:
Write efficient Javascript (PPT)
Efficient JavaScript
2. CSS Selectors
In most people's minds, the browser's parsing of CSS selectors is left-to-right, for example
#toc A {color: #444;}
Such a selector, if it is from right to left parsing is very efficient, because the first ID selection is basically to limit the scope of the lookup, but in fact, the browser to parse the selector from right to left. As in the above selector, the browser must traverse the ancestor node to find each a tag, and the efficiency is not as high as previously thought. Depending on the browser's line, there are a lot of things to be aware of when writing the selector, which is listed here for details.

3. HTML
The optimization of HTML itself is now becoming more and more of concern, see this summary article for details.

4. Image compression
Picture compression is a technical work, but now this aspect of the tool is also very much, compression often can bring good results, the specific compression principle and method in the "even Faster Web Sites" 10th chapter has a very detailed introduction, interested can go to see.
Summarize
This article from the page level and code level two granularity of the front-end optimization of the various ways to make a summary, these methods are basically front-end developers in the process of development can learn from and practice, in addition, complete front-end optimization should also include many other ways, such as CDN, Gzip, multi-domain, no Cookie server and so on, because of the developer's operability is not strong, there is not much to describe, detailed can refer to Yahoo and Google these "golden rules."

Original: http://www.qdfuns.com/notes/18892/168da392c447a172d3dd0d8e1754ca48.html

(GO) Web performance optimization

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.