Common JavaScript Optimization Methods

Source: Internet
Author: User
Tags browser cache

 

// For JavaScript beginners, I just saw a good <SPAN class = 'wp _ keywordlink '> Article </span> and shared it with you. 

 

For JavascriptCodeSpeed. We can generally divide it into two parts: download time and execution speed. Therefore, we can start with these two parts for optimization.

I. Optimized Code download speed

  1. In a single TCP-IP package, the maximum number of bytes can be put is 1160, so the size of each JS file, it is best not to exceed this number, in order to obtain the best download time.
  2. Merge JS files. If multiple JS external files are loaded on a page, it is best to merge them into one, which can effectively reduce the number of HTTP requests and save the download time.
  3. Use different domain names for external Js. We know that when a browser downloads a page, the maximum number of concurrent requests under the same domain name is certain (for example, IE6/7 is 2 under http1.0, while firefox3 is 6 ), therefore, if the Domain Name of the front-end page is www.phpblog.cn, the domain name of the external JS file can be changed to js.phpblog.cn, so that the browser can use the maximum number of concurrent downloads on the js.phpblog.cn domain name, this accelerates the download speed. (The above is just an example of my domain name. My website has not yet done so)
  4. Browser cache. The external JS files referenced on the page can be cached by the browser. The cache time is determined by the last-modified, etag, or expires in the header sent by the server to the client proxy. Therefore, the cache duration is long, it also becomes an aspect of the optimization speed. I recommend that you set the cache time for js to a long time. If you change the JS file, you can add a custom parameter after the JS file that references the URL, to force the client to download JS again. For example:

    <SCRIPT src = "http://js.phpblog.cn/jquery.js? Var = 2.0"
    Type = "text/JavaScript"> </SCRIPT>

  5. Delete comments, tabs, spaces, and line breaks in the Code. This effectively reduces the size of the JS file. We can use a ready-made tool to do this, for example, Google closure compiler that I have previously introduced.
  6. Replace the variable name with a longer variable name to reduce the size of the JS file. In this regard, Google closure compiler can also be used.
  7. Replace the Boolean value. We know that for comparison, true is equal to 1, and false is equal to 0. Therefore, the true and false values in the script can be replaced by 1 and 0, which can reduce several bytes.
  8. Array and object literal. For example, when defining an array, use VaR o = new [] instead of VaR o = new array. When defining an object, use VaR o =
    {} Instead of using VAR o = new object, they are completely equivalent.

Ii. Optimize code execution time

  1. Focus on the variable range. In JS, variable range is very important. We can think that the range of variables is a tree level in the browser. when looking for a variable, the browser will first look for it in the latest range. If not, it will be searched in its parent range. If it is not found, it will be searched in its parent range, until the window object range is found (the default global variable of the browser belongs to the window object ). This shows that making the browser find the variable as quickly as possible can speed up code execution. In JS, variables defined by VAR are local range variables, but variables defined by VAR are not global range variables. Therefore, if we use variables in a method, be sure to define it as a local variable so that the browser will not get the variable until it finds the window object. Another Optimization Technique Related to the variable range is not to use the with statement. Because the with statement creates another range and adds unnecessary searches.
  2. Reverse loop. When using the for loop, we often use the following:

    For (I = 0; I <100; I ++ ){}

    However, you need to know that after the loop is reversed, the speed will be faster:

    For (I = 100; I> = 0; I --){}

    This is because constant 0 is used as the basis for faster judgment. Of course, the while loop can also be reversed (converted to do... while). I will not go into detail here for the specific method.

  3. In addition to reversing the loop, we can also use loop merge to further speed up the loop. I have already introduced the method of loop merge in this article. Here it should be particularly noted that while loops can also be merged. The method is the same as the reverse loop, and do... while is also used for replacement.
  4. Use the built-in js method. For example, if you do not know that the math object has a POW () method, you may write a factorial calculation function by yourself, the efficiency of doing so is far inferior to calling the built-in method math directly. pow (), because the built-in method is compiled in C ++ or C language, the speed is much higher than the JS that explains the running.
  5. String connection optimization. The efficiency of using "+" to connect strings is very poor, especially when multiple strings are connected at a time, for example:

    VaR S = "A" + "B" + "C" + "D ";

    In this case, JS will perform multiple connection operations internally, resulting in a reduction in efficiency. To avoid this problem, we can use the array. Join () method instead:

    VaR A = ["A", "B", "C", "D"];
    VaR S = A. Join ();

  6. Store common values. In JS, accessing the attributes of an object is very expensive in terms of efficiency. Therefore, you can store the values used for multiple times in a variable. For example, the following code is slow:

    O1.style. Left = Document. Body. clientwidth;
    O2.style. Left =
    Document. Body. clientwidth;

    The following code is faster:

    VaR left = Document. Body. clientwidth;
    O1.style. Left =
    Left;
    O2.style. Left = left;

  7. In JS, the fewer statements in the script, the faster the execution speed. Based on this principle, we can know that using one VaR to define multiple variables is faster than multiple var definitions. For example:

    VaR A = 1, B = 2, c = 3;

    Faster:

    VaR A = 1;
    VaR B = 2;
    VaR c = 3;

    Similarly, the following code:

    VaR S = A [I ++];

    Faster:

    VaR S = A [I];
    I ++;

  8. Save on Dom usage. When JS is used to change the style of any element on the page (or add or delete elements), the browser will re-render the page. This overhead is not small. Therefore, when we operate the DOM multiple times in a row, we can first save all the changes to the DOM fragment, and then operate the page DOM at one time. For example:

    VaR arrtext = ["1", "2", "3", "4", "5", "6", "7", "8", "9 ", "10"];
    VaR
    Ofrag = Document. createdocumentfragment ();
    For (VAR I = 0; I
    {
    VaR
    OP = Document. createelement ("p ");
    VaR
    Otext = Document. createtextnode (arrtext [I]);
    Op. appendchild (otext );
    Ofrag. appendchild (OP );

    }
    Document. Body. appendchild (ofrag );

The above are just some of the optimization methods I know. Of course, the optimization methods in JS are certainly more than that. I can only introduce others and more methods. I also need to add them together.

 

 

 

------Yizero from http://www.phpblog.cn/archives/328

 

See yizero by yizero.com

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.