<< 回流与重绘:CSS性能让JavaScript变慢? « 张鑫旭-鑫空间-鑫生活 | 首页 | Fiddler (二) Script 用法 - 小坦克 - 博客园 >>

JavaScript性能优化的30个技巧

Tip #1 – Evaluate Local Variables

(http://blogs.msdn.com/b/ie/archive/2006/08/28/728654.aspx)

Primarily, specific to IE, because local variables are found based on the most to the least specific scope and can pass through multiple levels of scope, the look-ups can result in generic queries. When defining the function scope, within a local variable without a preceding var declaration, it is important to precede each variable with var in order to define the current scope in order to prevent the look-up and to speed up the code.

Tip #2 – Create shortcut codes to speed up coding

(http://www.spoonfeddesign.com/4-easy-tips-to-improve-javascript-efficiency)

For useful codes that are constantly being used, speeding up the coding process can be achieved by creating shortcuts for longer codes, for example, document.getElementById. By creating a shortcut, longer scripts will not take as long to code and will save time in the overall process.

Tip #3 –Manipulate element fragments before adding them to DOM

(http://www.jquery4u.com/dom-modification/improve-javascript-performance)

Before placing the elements to the DOM, ensure that all tweaks have been performed in order to improve JavaScript performance. This will eliminate the need to set aside Prepend or Append jQuery APIs.

Tip #4 – Save bytes by using Minification

(http://sixrevisions.com/web-development/10-ways-to-improve-your-web-page-performance)

Reduce the file size of your JavaScript documents by removing characters (tabs, source code documents, spaces etc.) without changing the functionality of the file.

There are a number of minification tools that can assist in this process, and have the ability to reverse the minification. Minification is the process of removing all unnecessary characters from source code, without changing its functionality.

Tip #5 –Don’t use nested loops if not required

(http://www.techstrut.com/2009/08/04/10-javascript-performance-tips)

Avoid unwanted loops, such as for/while, in order to keep the JavaScript linear and to prevent from having to go through thousands of objects. Unwanted loops can cause the browser to work harder to process the codes and can slow down the process.

Tip #6 – Cache objects to increase performance

(http://www.techstrut.com/2009/08/04/10-javascript-performance-tips)

Many times, scripts will be repeatedly used to access a certain object. By storing a repeated access object inside a user defined variable, as well as using a variable in subsequent references to that object, performance improvement can be achieved immediately.

Tip #7 – Use a .js file to cache scripts

(http://www.javascriptkit.com/javatutors/efficientjs.shtml)

By using this technique, increased performance can be achieved because it allows the browser to load the script once and will only recall it from cache should the page be reloaded or revisited.

Tip #8 – Place JavaScript at the bottom of the page

(http://developer.yahoo.com/blogs/ydn/posts/2007/07/high_performanc_5)

Placing the scripts as low as possible in the page will increase the rendering progress, and also increase download parallelization. The result is that the page will seem to load faster, and in some cases it can also save on the total amount of code needed.

Tip #9 – Use jQuery as a framework

(http://www.techstrut.com/2009/08/04/10-javascript-performance-tips)

Used for the scripting of HTML, jQuery is an easy to use JavaScript library that can help to speed up any website. jQuery provides a large number of plug-ins that can quickly be used, by even novice programmers.

Tip #10 – Compress your files with GZip

(http://devmoose.com/coding/10-ways-to-instantly-speed-up-your-website)

GZip can reduce a JavaScript file considerably, saving bandwidth, and accelerate the response time. JavaScript files can be very large, and without compression, it can bog down any website. Smaller files provide a faster and more satisfying web experience.

Tip #11- Don’t use “With” keyword

(http://blogs.msdn.com/b/ie/archive/2006/08/28/728654.aspx)

The “With” keyword is considered a black-sheep because it suffers from several flaws that can be very frustrating. Although it makes the process of working with local properties simpler, “With” can make looking up variables in other scopes more expensive.

Tip #12 – Minimize requests for HTTP

(http://www.websiteoptimization.com/speed/tweak/http)

Minimize HTTP requests to render pages by combining external files and including JavaScript directly within XHTML pages. Each time a unique HTTP takes a trip to a server, the result is a large number of delays.

Tip #13 – Implement Event Delegation

(http://www.djavaweb.com/blog/75-speed-up-your-webdevelop-smart-event-handlers.html)

With Event Delegation, it becomes easier to use a single event handler to manage a type of event for the entire page. Without using Event Delegation, large web applications can grind to a halt because of too many event handlers. Benefits of Event Delegation include; less functionality to manage, fewer ties between code and DOM, and less memory required to process.

Tip #14 – Don’t use the same script twice

(http://www.abhishekbharadwaj.com/2010/12/speed-up-your-website-avoid-duplicate-scripts)

Duplicate scripts will have a significant impact on performance. Duplicate scripts will create unnecessary requests on HTTP, especially in the IE browser. Using a SCRIPT tag, in an HTML page, will help to avoid accidentally duplicating scripts.

Tip #15 – Remove Double Dollar $$

(http://www.mellowmorning.com/2008/05/18/javascript-optimization-high-performance-js-apps)

Using “double dollar $$” function is not necessarily needed, when it comes to improving the speed of a website.

Tip #16 – Creating reference variables

(http://mondaybynoon.com/2009/04/27/a-couple-of-quick-tips-for-javascript-optimization)

When working with a specific node repeatedly, it is best to define a variable with that particular note, instead of switching to it repeatedly. This is not a significant enhancement but it can have a bigger impact on a large scale.

Tip #17 – Increase speed of Object Detection

(http://dean.edwards.name/weblog/2005/12/js-tip1)

A more efficient method to using Object Detection is to use a code created dynamically based off of object detection, rather than performing object detection inside of a function.

Tip #18 – Write effective Loops

(http://robertnyman.com/2008/04/11/javascript-loop-performance)

Depending on the browser, the method used to write Loops can have a great effect on the performance of a site. Improper writing of loops can slow down pages with lots of queries and running a number of loops in parallel.

Tip #19 – Shorten Scope Chains

(http://homepage.mac.com/rue/JS_Optimization_Techniques)

Global scopes can be slow, because each time a function executes, it cause a temporary calling scope to be created. JavaScript searchers for the first item in the scope chain, and if it doesn’t find the variable, it swells up the chain until it hits the global object.

Tip #20 – Index directly to NodeLists

(http://homepage.mac.com/rue/JS_Optimization_Techniques)

NodeLists are live and can take up a lot of memory, as they are updated when an underlying document changes. Its quicker to index directly into a list, as a browser will not need to create a node list object.

Tip #21 – Don’t use ‘eval’

(http://www.javascripttoolbox.com/bestpractices/#eval)

Although the “eval” function is a good method to run arbitrary code, each string that is passed to the eval function has to be parsed and executed on-the-fly. This cost has to be paid every time the execution reaches an eval function call.

Tip #22 – Use Function Inlining

(http://portal.acm.org/citation.cfm?id=844097)

Function Inlining helps to eliminate call costs, and replaces a function call with the body of the called function. In JavaScript, performing a function call is an expensive operation because it takes several preparatory steps to perform: allocating space for parameters, copying the parameters, and resolving the function name.

Tip #23 – Implement Common Sub-expression Elimination (CSE)

(http://sunilkumarn.wordpress.com/2010/10/19/common-subexpression-elimination-cse)

Common sub-expression elimination (CSE) is a performance-targeted compiler optimization technique that searches for instances of identical expressions and replaces them with a single variable holding the computed value. You can expect that using a single local variable for a common sub-expression will always be faster than leaving the code unchanged.

Tip #24 – Build DOM node and all its sub-nodes offline

(http://archive.devwebpro.com/devwebpro-39-0030514OptimizingJavaScriptforExecutionSpeed.html)

When adding complex content such as tables to a site, performance is improved by adding complex sub-trees offline.

Tip #25 – Try not to use global variables

(http://wiki.forum.nokia.com/index.php/JavaScript_Performance_Best_Practices#JavaScript_Performace_Best_Practices)

Because the scripting engine needs to look through the scope, when referencing global variables from within function or another scope, the variable will be destroyed when the local scope is lost. If variables in global scope cannot persist through the lifetime of the script, the performance will be improved.

Tip #26 – Use primitive functions operations vs. function calls

(http://wiki.forum.nokia.com/index.php/JavaScript_Performance_Best_Practices#JavaScript_Performace_Best_Practices)

Improved speed can be achieved in performance critical loops and functions by using equivalent primitive functions instead of function calls.

Tip #27 – Don’t retain alive references of other documents

(http://dev.opera.com/articles/view/efficient-javascript/?page=4#docreferences)

By not retaining alive references of other documents after the script has finished with them, faster performance will be achieved. This is because any references to those objects from that document are not to be kept in its entire DOM tree, and the scripting environment will not be kept alive in RAM. Thus the document itself is no longer loaded.

Tip #28 – Use XMLHttpRequest

(http://dev.opera.com/articles/view/efficient-javascript/?page=4#docreferences)

XMLHttpRequest helps to reduce the amount of content coming from the server, and avoids the performance impact of destroying and recreating the scripting environment in between page loads. Its is important to ensure that XMLHttpRequest is supported, or otherwise it can lead to problems and confusion.

Tip #29 – Avoid using try-catch-finally

(http://dev.opera.com/articles/view/efficient-javascript/?page=2)

Whenever the catch clause is executed, where the caught exception object is assigned to a variable, “try-catch-finally” creates a new variable in the current scope at runtime. A number of browsers do not handle this process efficiently because the variable is created and destroyed at runtime. Avoid it!

Tip #30 – Don’t misuse for-in

(http://dev.opera.com/articles/view/efficient-javascript/?page=2)

Because the “for-in” loop requires the script engine to build a list of all the enumerable properties, coding inside for loop does not modify the array. It iterates pre-compute the length of the array into a variable len inside for loop scope.

阅读全文……




发表评论 发送引用通报