Website Optimization-page optimization

Source: Internet
Author: User
The efficiency and the starting pace and the richness of functions are mutually constrained. Recently, I am busy working on functions. I know that some areas can be optimized first, but I am a freshman, so you can do it right away.
In the eyes of the boss, after a good optimization, it can be no longer optimized, or it takes only a small amount of time to maintain, but I do not know, optimization is a continuous process, the idea cannot keep up with changes.
It's hard to be human, and it's harder to do things!

It is worth thinking about how to start optimization, how to start, and what to do.

Optimization Principles:
1. optimization continues. When you start to create a function, optimization begins. However, we often think that the new function is a well-optimized function, but we do not know that this function may affect other functions,
Or, you can set the function to 70% first and then optimize it later.
2. Do not optimize it when it is not necessary. Users have a certain degree of patience in performance. Sometimes a small loading icon can make users feel satisfied.
3. During optimization, We need to write down the use cases to drive the optimization. Under what conditions should the test results be tested? With the test cases available, we can be targeted. During optimization, we need to save a snapshot of the system; with this historical information, we can better compare and find out the shortcomings and the areas that need to be further optimized.
4. The optimization is aimed at the bottleneck of the system. Find the performance bottleneck of the system and break it through. What we get is twice the result with half the effort.

Where can I start with page optimization for a website?
A web page has three stages in its lifecycle:
1 Load
2 Rendering
3. respond to user interaction

Different optimization strategies are required for these three phases:
1 For the loading phase:
The core of loading is network transmission. Therefore, the focus is to minimize the number of pages and place them in the closest place to the user, so loading is faster. For detailed implementation rules, see <a href = "http://developer.yahoo.com/performance/"> 14 yahoo suggestions </a> <a href = "http://msdn2.microsoft.com/en-us/library/ms533020.aspx#Close_Your_Tags">
Abstract:
If it is not easy, you need to remove useless information from the page and compress gzip.
1) Use </a> <a href = "http://developer.yahoo.com/yui/compressor/"> yui compressor </a> to compress css and js
2) Merge js and css files and use tools such as jsmin.
3) compress the image and merge the background image. Commonly used tools <a href = "http://pmt.sourceforge.net/pngcrush/"> PngCrush </a>, <a href = "http://psydk.org/PngOptimizer.php"> PngOptimizer </a>.
4) Delayed loading: The materials are loaded only when the user uses the corresponding materials.
If it is closest to the user, it is the user's browser cache. Therefore, we need to set the expiration time of page elements as long as possible, so that all the cache can be cached, and all the content that can be placed on the cdn can be put on the cdn.

2 For the rendering phase:
The core of the rendering phase is to allow users to see the page display as soon as possible and interact with the page. Therefore, the focus is to display the content of the first screen, so that users can see the page early and feel the interaction.
1. If the first screen of the page is displayed, the js Code event needs to be processed after the dom tree is built, just like the jquery ready event.
2. Disable some labels in html that can be disabled by default as soon as possible. This will also help increase the rendering speed. If it is OK to let the browser determine when to close it, it will take a lot of backtracking operations, and it will take a lot of money.
<A href = "http://msdn2.microsoft.com/en-us/library/ms533020.aspx#Close_Your_Tags"> msdn has a detailed description of Close Your HTML Tags </a>
Unlike XML, HTML has the notion of implicitly closed tags. this includes des frame, img, li, and p. if you don't close these tags, Internet Explorer renders your pages just fine. if you do close your tags, Internet Explorer will render your pages even faster.
3. Delayed loading of some large images. Due to the limited number of concurrent connections in the browser, some large images will be blocked, so try to delay loading as much as possible, or load as needed, rendering speed will be faster
4. output the content in the web Server Buffer as early as possible, and the time when the browser starts rendering is displayed.
5. Do not rely on js Code to display the first screen of the page. This is very important. In this way, some of your css and js files can be loaded in late without affecting the display of the first screen.
6. When loading the page onload, you can consider doing some pre-loading tasks to pre-load the materials required for other pages. Search engines such as google and yahoo are doing this, and some large background images are quietly loaded.

& Lt; script & gt;

Window. onload = function (){
Var script = document. createElement ("script ");
Script. src = ...;
Document. body. appendChild (script );
};

& Lt;/script & gt;

4. For the running stage:
The core of the runtime stage is the optimization of js Code. Based on the execution principle of js Code, write efficient js Code.
1) principle of using proximity to variables
Js has the concept of scope chain. If this scope cannot be found, it will be found in the previous scope. If there are too many global variables, each time variables are used, various scopes will be checked at different layers, and the performance will be expensive.
Remember to add var when declaring the variable. Otherwise, the variable will be placed in the top-level scope of window.
Do not use with to traverse. It will stop the js actuator from searching locally, but traverse the function chain for searching.
Use local variables to cache some unused global variables.
Var arr = ...;
Var globalVar = 0;
(Function (){
Var I;
For (I = 0; I & lt; arr. length; I ++ ){
GlobalVar ++;
}
})();

Var arr = ...;
Var globalVar = 0;
(Function (){
Var I, l, localVar;
L = arr. length;
LocalVar = globalVar;
For (I = 0; I & lt; l; I ++ ){
LocalVar ++;
}
GlobalVar = localVar;
})();
2) The same applies to prototype chains. Avoid prototype chain traversal whenever possible.

Function (){}
A. prototype. prop1 = 1;

Function B (){
This. prop2 = 2;
} B. prototype = new ();

Var B = new B ();
Alert (B. prop1 );

To read the property prop1 from B, we need to traverse from the prototype chain of B to the ptototype chain of a. Think about the result if the chain is long.

3) prototype. If you want to create many objects, we recommend that you put the common methods of the objects in prototype instead of in the constructor.
Because prototype is public, constructor requires initialization for each object, which saves a lot of memory.
You can use prototype to increase the search time of object members.

Function Foo (){...}
Foo. prototype. bar = function (){...};
Function Foo (){
This. bar = function (){...};
}

4) do not use eval unless the performance is not a problem or you must use eval to solve the problem.
Similarly, in seTtimeout or setInterval, it is best to use an anonymous function. Using a string will result in an eval operation.

SetTimeout (function (){
// Business Code
}, 50 );

5) string connection operations, especially loop connection operations, may cause frequent copies of temporary variables (such as realloc in C language) in some ie browsers ), we recommend that you use the join method of the Array object.
For more information, see <a href = "http://blog.goguoguo.com/html/y2009/142.html"> javascript optimization </a>

Var I, s = "";
For (I = 0; I & lt; 10000; I ++ ){
S + = "x ";
}
Var I, s = [];
For (I = 0; I & lt; 10000; I ++ ){
S [I] = "x ";
}
S = s. join ("");

6) Unless the Regexp object is used as few as possible to dynamically build a regular expression, and to determine whether a string matches, we recommend using test instead of exec. exec has some performance problems.
Also, the regular expression should be as simple as possible. If it is complicated, think about string matching back and forth, and the complexity will be improved a lot.

7) use the cache whenever possible, especially for large datasets used in some loops, which are relatively stable and only a large number of read operations.
// No cache is used. Every call generates v
Var fn = (function (){
Var B = false, v;
Return function (){
If (! B ){
V = ...;
B = true;
}
Return v;
};
})();

// Store v In fn
Function fn (){
If (! Fn. B ){
Fn. v = ...;
Fn. B = true;
}
Return fn. v;
}
// Delayed Loading
Var fn = function (){
Var v = ...;
Return (fn = function (){
Return v;
})();
};

7) for processing large datasets, try to put them in the server. js has no advantage in processing large datasets.
Do not make JavaScript Execution cause the ui to be blocked. This effect is too bad.
Try to use the long-time JavaScript code in setTimeout blocks. Each block should not exceed 300 ms. Otherwise, the user will have comments.

Function doSomething (callbackFn ){

// Perform initialization.
(Function (){
// Do a small job, not long
If (termination condition ){
CallbackFn ();
} Else {
// Execute the next block
SetTimeout (arguments. callee, 0 );
}

})();
}

This is the same as ajax, with multithreading and small pieces of execution to improve the efficiency of ui interaction.

8) primitive operations have much higher performance than functions. Try to use primitive operations
// Less than the operation
Var a = 1, B = 2, c;
C = Math. min (a, B );
C = a <B? A: B;
// Array Operation
MyArray. push (value );
MyArray [myArray. length] = value;
MyArray [idx ++] = value;

9) exception handling is rarely used in loop or performance critical points, because exception handling requires poor stack information to be saved.
// It is unwise to use try and cache in a loop
Var I;
For (I = 0; I <100000; I ++ ){
Try {
...
} Catch (e ){
...
}
}

// Extract try and cache
Var I;
Try {
For (I = 0; I <100000; I ++ ){
...
}
} Catch (e ){
...
}

10) at the key points of performance, for, in and with operations are rarely used, because prototype chain search is involved.
Var key, value;
For (key in myArray ){
Value = myArray [key];
...
}
// Replace the value with an array.
Var I, value, length = myArray. length;
For (I = 0; I <length; I ++ ){
Value = myArray [I];
...
}

11) define it outside the if and else branches if the branches are the same.
Function fn (){
If (...){
...
} Else {
...
}
}
Var fn;
If (...){
Fn = function (){...};
} Else {
Fn = function (){...};
}

12) when operating the dom tree, use innerHtml for one-time construction instead of append.
However, innerHtml may also pose a lot of risks, such as inserting script phishing scripts. For more information, see
<A href = "http://www.julienlecomte.net/blog/2007/12/38/"> The Problem With innerHTML </a>
Var I, j, el, table, tbody, row, cell;
El = document. createElement ("div ");
Document. body. appendChild (el );
Table = document. createElement ("table ");
El. appendChild (table );
Tbody = document. createElement ("tbody ");
Table. appendChild (tbody );
For (I = 0; I <1000; I ++ ){
Row = document. createElement ("tr ");
For (j = 0; j <5; j ++ ){
Cell = document. createElement ("td ");
Row. appendChild (cell );
}
Tbody. appendChild (row );
}

Var I, j, el, idx, html;
Idx = 0;
Html = [];
Html [idx ++] = "<table> ";
For (I = 0; I <1000; I ++ ){
Html [idx ++] = "<tr> ";
For (j = 0; j <5; j ++ ){
Html [idx ++] = "<td> </td> ";
}
Html [idx ++] = "</tr> ";
}
Html [idx ++] = "</table> ";
El = document. createElement ("div ");
Document. body. appendChild (el );
El. innerHTML = html. join ("");

13) Try to use clone when modifying the dom tree, instead of creating it dynamically.
At least a lot of initialization time can be saved.
Var I, j, el, table, tbody, row, cell;
El = document. createElement ("div ");
Document. body. appendChild (el );
Table = document. createElement ("table ");
El. appendChild (table );
Tbody = document. createElement ("tbody ");
Table. appendChild (tbody );
For (I = 0; I <1000; I ++ ){
Row = document. createElement ("tr ");
For (j = 0; j <5; j ++ ){
Cell = document. createElement ("td ");
Row. appendChild (cell );
}
Tbody. appendChild (row );
}

Var I, el, table, tbody, template, row, cell;
El = document. createElement ("div ");
Document. body. appendChild (el );
Table = document. createElement ("table ");
El. appendChild (table );
Tbody = document. createElement ("tbody ");
Table. appendChild (tbody );
Template = document. createElement ("tr ");
For (I = 0; I <5; I ++ ){
Cell = document. createElement ("td ");
Template. appendChild (cell );
}
For (I = 0; I <1000; I ++ ){
Row = template. cloneNode (true );
Tbody. appendChild (row );
}

14) Use documentfragment
Var I, j, el, table, tbody, row, cell, docFragment;
DocFragment = document. createDocumentFragment ();
El = document. createElement ("div ");
DocFragment. appendChild (el );
Table = document. createElement ("table ");
El. appendChild (table );
Tbody = document. createElement ("tbody ");
Table. appendChild (tbody );
For (I = 0; I <1000; I ++ ){
...
}
Document. body. appendChild (docFragment );

15) when binding events, try to bind them to the subset of the least page elements.
Using the jquery selector, we often choose a lot of elements at once, each, and then bind the event processing function.
If the selected collection is large, not only does it take time to bind it to event processing.
When appropriate, you can use the event bubbling mechanism to bind events.

To quickly display pages, js optimization is not enough, and css needs to be optimized accordingly.
Css optimization points:
1) css sprite merge background images
2) js should not be involved in the layout. In this way, the page can be displayed normally without js,
You can load the js file in the rear meter.
3) do not use ie expressions or use ie filters.
4) Optimize the table layout so that the table can be rendered before receiving all the data homes.
Use table-layout: fixed
Explicitly define a COL element for each column
Set the WIDTH attribute on each col

We will also follow up on ajax optimization and some common optimization tools.

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.