JavaScript project optimization Summary

Source: Internet
Author: User

Some time ago, we optimized the JavaScript code of the company's existing projects. This article summarizes the optimization work and shares it with you. Of course, my optimization method may not be the best, or something wrong, please advise. The summary of JavaScript optimization is divided into the following aspects: Comparison of the optimization before and after optimization the code is chaotic, the same function repeatedly appears in multiple places. If you need to modify the implementation, you need to find all the places. The entire body is modularized, and the public interface is extracted into a library with clear structure, convenient code reuse, and the game can prevent variable pollution. JavaScript files are not compressed, and the size is relatively large, which consumes a lot of time on the network. Blocking page rendering JavaScript public library files are compressed using UglifyJS: ● the Size is small and the network loading time is optimized ● The compression obfuscated the code, to a certain extent, it is necessary to load multiple individual JavaScript files when using the code, increasing the number of http requests and reducing the performance. Merge and compress Public Libraries while reducing the size, reducing the number of http requests lacks documentation (this makes the subsequent developers unclear about the existing functions, which, to some extent, causes the same function to appear in multiple places) every class, function, and attribute in the public library is described in this document. ● modularization (class programming): the code is clear, effective in preventing variable contamination, code reuse is convenient, and so on; ● JavaScript compression obfuscation: reduce the size to optimize the loading time and obfuscation to protect code; ● JavaScript file merging: Reduces the time consumed by http requests to optimize the network and improves performance; ● generate documents: facilitates the use of public libraries and facilitates searching for interfaces. Modularization (class programming) for static classes, JavaScript implementation is relatively simple, and it is enough to use the direct volume of objects. However, you need to do some work to create instantiation and inherit classic classes. Because JavaScript is a prototype-based programming language that does not contain built-in class implementations (it does not have an access control operator and does not have a class keyword defined, it does not support inherited extend or colons, nor is it used to support virtual functions, etc.), but we can easily simulate a classic class through JavaScript. Static classes do not need to be instantiated based on the characteristics of the common interfaces of baby JS, so this method is used for optimization. The following uses PetConfigParser as an example to describe the implementation method: var PetConfigParser; if (! PetConfigParser) {PetConfigParser ={};} (function () {// private variable, function/*** all baby configuration dictionaries, with [cate * 10000 + (lvl-1) * 10 + dex-1] is key * @ attribute petDic * @ type {Object} * @ private */var petDic = null; // baby dictionary/*** construct an Object dictionary based on _ pet_config, use the combination of cate, dex, and lvl as the key * @ method buildPetDic * @ private * @ return {void} */function buildPetDic () {petDic = new Object (); for (var item in _ pet_config) {v Ar lvl = parseInt (_ pet_config [item] ['lvl']); var dex = parseInt (_ pet_config [item] ['dex ']); var cate = parseInt (_ pet_config [item] ['cate']); var key = cate * 10000 + (lvl-1) * 10 + dex; petDic [key] = _ pet_config [item] ;}// public interface/*** according to the baby id, read the information of the corresponding baby in _ pet_config * @ method getPetById * @ param {String/int} petId baby id * @ return {Object} All static information of pet baby, for example, {id: "300003289", lvl: "1", dex: "2", pr Ice: "200", life: "2592000", cate: "3", name: "Apsara tips: Level 1 proficiency 2", intro: "", skill: "Amulet ", skill1_prob: "30", skill2_prob: "0"} */if (typeof PetConfigParser. getPetById! = 'Function') {PetConfigParser. getPetById = function (petId) {var pet = ("undefined" = typeof (_ pet_config ))? Null: _ pet_config ["pet _" + petId]; return pet ;}}) (); this method uses JavaScript anonymous functions to create private scopes, these private scopes can only be accessed internally. To sum up the above processes, we can take the following steps: 1) define a global variable (var PetConfigParser). Note the differences between the upper-case and normal variables; 2) then create an anonymous function and run (function () {/* xxxx */}) ();) to create local variables and functions in the anonymous function, they can only be accessed in the current scope; 3) global variables (var PetConfigParser) can be accessed anywhere, and PetConfigParser can be operated inside anonymous functions to add static functions. Use instance: $ (function () {DialogManager. init (); $ ('# showDialog '). click (function () {DialogManager. show ("# msgBoxTest", "# closeId"); return false ;}); $ ('# cofirmBtn '). click (function () {DialogManager. hide (); return false ;}) typical classes are implemented in the instance type JavaScript. Three methods are summarized: ● constructor method; ● prototype method; ● constructor + prototype: A hybrid constructor is used to initialize the attributes and values of an instance object. Any JavaScript function can be used as a constructor. The constructor must use the new operator as the prefix to create a new instance. Var Person = function (name) {this. name = name; this. sayName = function () {alert (this. name) ;}}// instantiate var Taylor = new Person ("tylerzhu"); var saylor = new Person ("saylorzhu"); Taylor. sayName (); saylor. sayName (); // check the instance alert (Taylor instanceof Person); whether the constructor method is familiar with the traditional object-oriented language! Only the class keyword is replaced with function. Note: Do not omit new. Otherwise, Person ("tylerzhu") // ==> undefined. When the new keyword is used to call the constructor, the execution context changes from the Global Object (window) to an empty context, which represents the new instance. Therefore, this key child points to the currently created instance. When new is omitted, if no context switch is performed, the name will be searched for in the global object. If no name is found, a global variable name will be created and undefined will be returned. The prototype constructor method is simple, but there is a waste of memory. In the above example, two objects, Taylor and saylor, are instantiated. On the surface, there seems to be no problem, but the sayName () method is actually the same for each instance object, each time an instance is generated, all must be repeated content applications. Alert (Taylor. sayName = saylor. sayName) Outputs false !!! Each constructor in Javascript has a prototype attribute pointing to another object. All attributes and methods of this object will be shared by the constructor instance. Var Person = function (name) {Person. prototype = name; Person. prototype. sayName = function () {alert (this. name) ;}// instantiate var Taylor = new Person ("tylerzhu"); var saylor = new Person ("saylorzhu"); Taylor. sayName (); saylor. sayName (); // check the instance alert (Taylor instanceof Person); in this case, the sayName method of the instance of Taylor and saylor is the same memory address (pointing to the prototype object ), therefore, the prototype method saves more memory. But let's look at the output of Taylor. sayName (); saylor. sayName (); both of them, we can see the problem-they all output "saylorzhu ". Because all attributes of the prototype are shared, as long as one instance changes other attributes, the instantiated object saylor overwrites Taylor. The constructor + prototype hybrid constructor can allocate different memory for each object of the same class, which is suitable for setting attributes when writing classes; however, when setting the method, we need to share different objects in the same class with the same memory. The writing method is best in prototype mode. Therefore, when writing a class, you need to mix the constructor method and the prototype method (many class libraries provide the methods for creating classes or the writing methods of the framework are essentially: constructor + prototype ). Var Person = function (name) {Person. prototype = name; Person. prototype. sayName = function () {alert (this. name) ;}// instantiate var Taylor = new Person ("tylerzhu"); var saylor = new Person ("saylorzhu"); Taylor. sayName (); saylor. sayName (); // check the instance alert (Taylor instanceof Person); in this way, users with different names can be constructed by using the constructor. The object instances also share the sayName method without causing memory waste. JavaScript compression/merge JavaScript code compression obfuscation: Simply put, to reduce the js file size, remove unnecessary comments and line feed indentation, make the download faster and improve the user experience. There are many JavaScript compression tools. I recommend using the UglifyJS tool currently used by jQuery (jQuery has used many compression tools before, such as Packer) because of its excellent compression performance. "When jQuery 1.5 was released, john resig said that the code optimization program used was switched from Google Closure to UglifyJS, and the compression effect of the new tool was very satisfactory"

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.