Best practices for advanced programming of JavaScript

Source: Internet
Author: User
Tags tagname

First, maintainability: understandable, intuitive, adaptable, scalable, and can be debugged
  1. Code Conventions:
      1. Readability
        1. Formatting: Recommended indent size is 4 spaces
        2. Comments: Functions and methods, large-segment code, complex algorithms, hack
      2. Variable and function naming
        1. Variable name is noun
        2. Function name begins with a verb
        3. Variables and functions use the name of the logical character, don't worry about the length.
      3. Variable type transparency: three ways to represent variable types
        1. Initialize: var found = false; Boolean type
        2. Use the Hungarian notation to specify the variable type: O for object, s for string, I for integer, F for floating-point, and B for Boolean
        3. Usage type comment: var found/*:boolen*/= false;
  2. Loose coupling:
    1. Decoupling Html/javascript
        1. HTML contains JavaScript, example: <script type= "Text/javascript" >document.write ("Hello world!") </script>; Tightly coupled <script> tags
          <input type= "button" value= "click Me" onclick= "dosomething ();" />//Event attribute values tightly coupled
        2. Ideally: HTML and JavaScript should be completely detached and include JavaScript through external files and using the DOM attach behavior.
          Issue: JavaScript errors can be judged either in HTML or in JavaScript, and when the button is pressed before DoSomething () is available, a JavaScript error is also raised.
        3. JavaScript contains html,javascript to generate HTML, which should be avoided, and maintaining a hierarchical separation helps to determine the source of the error easily .
        4. Ideal: When JavaScript is used to insert data, try not to insert tags directly, You can control the display and concealment of the markup, rather than generate it. Another approach is to make AJAX requests and get more HTML to display, which allows the same rendering layer (PHP, JSP, Ruby) to output markup.
    2. Decoupling Css/javascript
        1. When you modify a style with JavaScript, you should do so by dynamically modifying the style class instead of a specific style.
        2. The only source that shows the problem should be CSS, and the only source of behavioral problems should be JavaScript.
    3. Decoupling application logic/event handlers
        1. The application logic and event handlers are separated, and an event handler should get relevant information from the event object and pass that information to a method that handles the application.
        2. Benefits: You can more easily change the events that trigger a particular process, and second you can test the code without attaching to the event, making it easier to create unit tests or automated application processes.
        3. Several principles of loose coupling between application and business logic:
          1. Do not pass the event object to another method; only the data required from the event object is transmitted;
          2. Any action at the application level should be done without executing any event handlers.
          3. Any event handler should handle the event and then transfer the processing to the application logic.
  3. Programming Practices:
      1. Respect for object ownership: If you are not responsible for creating and maintaining an object, its objects, or its methods, you cannot modify them.
        1. Do not add attributes to instances or prototypes;
        2. Do not add methods to instances or prototypes;
        3. Do not redefine a method that already exists.
      2. Avoid global variables: Create at most one global amount so that other objects and functions exist.
      3. Avoid comparisons with null
        1. If the value should be a reference type, use the instanceof operator to check its constructor.
        2. If the value should be a base type, use typeof to check its type.
        3. If you want the object to contain a particular method name, use the typeof operator to ensure that the method that specifies the name exists on the object.
      4. Using constants
        1. The key is separating the data from the logic that uses it
        2. Duplicate values: Any value that is used in multiple places should be extracted as a constant and also contains the CSS class name, which limits the error that can result when one value changes and the other does not.
        3. User interface strings: Easy internationalization
        4. URLs: Resource locations are easily changed in Web applications, so it is recommended to store all URLs in a common place
        5. Any value that may change

Second, to ensure code performance
  1. Note scope:
    1. Avoid global lookups: using global variables and functions is certainly more expensive than local, because it involves lookups on the scope chain.
        1. Sample code:
          Function UpdateUI () {
              var IMGs = document.getElementsByTagName ("img");
            & nbsp for (Var i=0,len=imgs.length;i<len;i++)
              {
                  Imgs[i].title = Document.ti Tle + "image" + i;
             }
              var msg = document.getElementById ("msg");
              msg.innerhtml = "Update complete.";
          }

        2. optimized code

          Function UpdateUI () {
               var doc = document;
               var imgs = doc .getelementsbytagname ("img");
              
              for (var i=0,len=imgs.length;i<len;i++)
              {
              ;      imgs[i].title = doc .title + "image" + i;
             }
               var msg = doc .getelementbyid ("msg");
              msg.innerhtml = "Update complete.";
          }

    2. Avoid the WITH statement: You must avoid using the WITH statement where performance is important.
        1. Like functions, the WITH statement creates its own scope, which is sure to increase the length of the scope chain in which the code executes.
        2. There are few cases where the WITH statement must be used, and it is primarily used to eliminate extra characters . In most cases, you can use local variables to do the same thing without introducing a new scope.
        3. Instance code:
          function Updatebody () {
          With (Document.body) {
          alert (tagName);
          InnerHTML = "Hello world!";
          }
          }
          The improved Code:

          function Updatebody () {
          var body = document.body;
          alert (body.tagname);
          body.innerhtml = "Hello world!";
          }

  2. Choose the Right method
    1. Avoid unnecessary property lookups
        1. Constant value O (1): Refers to the value of the literal and stored in the variable, accessing the array element
        2. To the value O (log n):
        3. Linear O (n): Accessing an object, any property lookup on an object takes longer than accessing a variable or array, because a property with that name must be searched in the prototype chain, and the more property is searched, the longer it takes to execute.
          Once the object property is used multiple times, it should be stored in a local variable.
        4. Square O (n2):
    2. Optimize loops: The basic steps are as follows:
        1. Impairment iterations: In many cases, iterators with constant impairment in the loop are more efficient, starting with the maximum value.
        2. Simplified termination Condition: Because the termination condition is calculated for each cycle, it must be guaranteed as fast as possible. This means avoiding property lookups or other O (n) operations.
        3. Simplify the loop body: The loop body is the most executed, so make sure it is optimized to the maximum extent possible. Make sure there are no dense calculations that can be easily removed from the loop.
        4. Post-Test loop: The most commonly used for and while loops are pre-test loops , and, like Do-while, this post-test loop avoids the calculation of the initial termination condition and therefore runs faster.
        5. Example code:
          for (var i=0; i < values.length; i++) {
          Process (Value[i]);
          }
          Impairment Iteration Optimization:
          For (var i=values.length; I >= 0; i--) {
          Process (Value[i]);
          }

          Post-Test loop optimization: Remember to use a post-test loop to make sure that you have at least one value to process, and that an empty array results in an extra loop and the front test loop can be avoided.
          var i = values.length-1;
          if (i >-1) {
          do{

          Process (Values[i]);
          }while (-i. > 0);
          }


    3. Expand Loops
      1. When the number of loops is determined, eliminating loops and using multiple function calls tends to be faster.
      2. If the number of iterations in the loop cannot be determined beforehand, you can use the Duff appliance technology, which is named after the creator Tom Duff and is used in the C language as early as possible. Jeff Greenberg implements the Duff device with JavaScript, and the basic concept is to expand a loop into a series of statements by calculating whether the number of iterations is a multiple of 8.
      3. Jeff Greenberg's Duff device technical code: Calculates a loop that requires multiple iterations by dividing the number of elements in the values array by 8来.
        Credit:jeff Greenberg for JS implementation of Duff ' s Device
        Suppose values.length > 0
        var iterations = Math.ceil (VALUES.LENGTH/8);
        var startAt = values.length% 8;
        var i = 0;

        do{
        Switch (startAt) {
        Case 0:process (values[i++]);
        Case 1:process (values[i++]);
        Case 2:process (values[i++]);
        Case 3:process (values[i++]);
        Case 4:process (values[i++]);
        Case 5:process (values[i++]);

        Case 6:process (values[i++]);
        Case 7:process (values[i++]);
            }

        startAt = 0;
        } while (--iterations > 0);


      4. By Andrew B.king's speed-up your Site (New riders,2003), a faster Duff device technology was proposed, dividing the do-while cycle into 2 separate loops. Here is an example:
        Credit:speed up your Site (New riders,2003)
        var iterations = Math.floor (VALUES.LENGTH/8);
        var leftover = values.length% 8;

        if (Leftover > 0) {
        do{
        Process (values[i++]);
        }while (--leftover > 0);
        }
        do{
        Process (values[i++]);
        Process (values[i++]);
        Process (values[i++]);
        Process (values[i++]);
        Process (values[i++]);
        Process (values[i++]);
        Process (values[i++]);
        Process (values[i++]);
        }while (--iterations > 0);

      5. In this implementation, the remainder of the calculation is not processed in the actual loop, but is divided by 8 in an initialization loop. This method is almost 40% faster than the original Duff device when the extra elements are processed and the main loop of 8 process () calls is resumed.
      6. Using an expansion loop for big data sets can save a lot of time, but for small datasets, the extra overhead may outweigh the cost.

    4. Avoid double interpretation: there is a double interpretation penalty when JavaScript code wants to parse JavaScript. This happens when you use the Eval function or the function constructor and use settimeout () to pass a string argument.
      Instance code:
      Some code evaluation---avoid
      Eval ("alert (' Hello world! ')");

      Create a new function---avoid
      var sayhi = new Function ("alert (' Hello world! ')");

      Set Timeout---Avoid
      SetTimeout ("alert (' Hello world! ')", 500);

      Analysis: The above code to parse the string containing JavaScript code, this operation can not be completed in the initial parsing process, because the code is contained in the string, that is, the JavaScript code must be running while the new parser to start parsing new code.

      Revised Example:
      has been fixed
      Alert (' Hello world! ');

      Create new Function---modified
      var sayhi = function () {
      Alert (' Hello world! ');
      };

      Set a timeout---fixed
      SetTimeout (function () {
      Alert (' Hello world! ');
      },500);
    5. Additional Considerations for performance:
        1. Native methods are faster: Native methods are written in compiled languages such as C + +, so much faster than JavaScript. The easiest thing to forget about JavaScript is the complex mathematical operations that can be found in the Math object, which are much faster than any of the same methods of using JavaScript, such as sine and cosine.
        2. Switch statement faster
        3. Bit operators are faster: modulo, logical, and logical OR

  3. Minimize the number of statements: The number of statements in the JavaScript code also affects the speed of the operations performed. A single statement that completes multiple operations is faster than multiple statements that complete a single operation.
      1. Multiple variable declarations
      2. Inserting iteration values
      3. Using the Vegetarian Group and object literals
  4. Optimizing DOM Interaction
    1. Minimized on-site updates
      1. Onsite update: You need to update the user's display on the page immediately (on site). Every change, whether it's inserting a single character or removing an entire fragment, has a performance penalty because the browser is recalculating countless dimensions to update.
      2. Instance code:
        var list = document.getElementById ("MyList"),
        Item
        I
        for (i = 0; I < 10;i + +) {
        Item = document.createelement ("Li");
        List = AppendChild (item);
        Item.append (document.createTextNode ("Item" + i));
        }
        Analysis: The code adds 2 live updates for each project: One add <li> element, and the other adds a text node to it. A total of 20 onsite updates are required. Two optimization methods: the first one to remove the list from the page, and finally to update, and then plug the list back to the same location, this method is not ideal, because each time the page updates will be unnecessary flashing. The second approach is to use a document fragment to build the DOM structure and then add it to the list element, which avoids field updates and page flicker issues.
        Optimized code:
        var list = document.getElementById ("MyList"),
        fragment.document.createDocumentFragment (),
        Item
        I
        for (i = 0; I < 10;i + +) {
        Item = document.createelement ("Li");
        fragment.appendchild (item);
        Item.appendchild (document.createTextNode ("item" + i));
        }

        List.appendchild (fragment);

    2. Using innerHTML:
        1. The methods for creating DOM nodes in the page are: using DOM methods such as createelement () and AppendChild (), and using innerHTML. Both methods are similar in efficiency for small dom changes. For large DOM changes, however, using innerHTML is much faster than creating the same DOM structure using standard DOM methods.
        2. because when innerHTML is set to a value, the background creates an HTML parser and then uses the internal DOM call to create the DOM structure, not the JavaScript-based DOM invocation. Because the internal method is compiled rather than interpreted, execution is much faster.
        3. The key to calling innerHTML (as with other DOM operations) is to minimize the number of times it is called.
    3. Using the event Proxy
        1. There is a negative correlation between the number of event handlers on the page and the speed at which the page responds to user interaction, and it is best to use event proxies to mitigate this penalty.
        2. Event agents use event bubbling, and any event that can be bubbled can be handled not only on the event target, but also on any ancestor node of the target, so you can attach the event handler to higher-level event handling for multiple targets, and if you attach event handlers at the document level, Can handle the entire page of events.
    4. Note Htmlcollection
        1. Access to htmlcollection, whether it is a property or a method, is a query on the document, and this query is expensive and minimizing the number of accesses to htmlcolletcion can greatly improve script performance.
        2. The most important place to optimize htmlcollection access is the loop
          Instance code:
          var images = document.getelementsbytagname ("img"),image, I,len;

          For (I=0,len=images.length;i < len;i++) {
          image = Images[i];
          Processing
          }
        3. When will the Htmlcollection object be returned:
          1. A call to getElementsByTagName () was made
          2. Gets the ChildNodes property of the element
          3. Gets the attributes property of the element
          4. Special collections are accessed, such as Document.forms, Document.images, and so on.

Best practices for advanced programming of JavaScript

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.