jQuery Code and Syntax Guidelines for Improved Code Performance

If you want to publish your jQuery plugins following jQuery core code writing guidelines is a good idea. Here are some of the guidelines.

    • Do NOT append an element to the DOM in your loop.

      [code:js]// DO NOT DO THIS
      for (var i=0; i<=rows.length; i++)
      {
      $(‘#myTable’).append(‘<tr><td>’+rows[i]+'</td></tr>’); }

      // INSTEAD DO THIS
      var tmp = ”;
      for (var i=0; i<=rows.length; i++)
      {
      tmp += ‘<tr><td>’+rows[i]+'</td></tr>’;
      }
      $(‘#myTable’).append(tmp);[/code]

        • Don’t use string concatenation, instead use array’s join() method for a very long strings.

          [code:js]var tmp = [];
          tmp[0] = ‘<tbody>’;
          for (var i=1; i<=rows.length; i++)
          {
          tmp[i] = ‘<tr><td>’+rows[i-1]+'</td></tr>’;
          }
          tmp[tmp.length] = ‘</tbody>’;
          $(‘#myTable’).append(tmp.join(”));[/code]

          • Don’t use "string".match() for RegExp, instead use .test() or .exec()
          • Local variables are declared and initialized on one line just below the function declaration with no extra line:

          [code:js]function someFunction () {
          var target = arguments[0] || {}, i = 1, name;

          // Empty line and then the rest of the code
          }[/code]

          • All strings are in double quotes " ", not single quotes ‘ ‘:
          • The last but not least, variable naming uses camelCase.

          See more details