Some time ago, we optimized the JavaScript code of the company's existing projects. This article is a summary of the optimization work, and I will share it with you. Of course, my optimization method may not be optimal, or there may be something wrong. Please enlighten me.
JavaScript optimization summary is divided into the following points
Comparison before and after optimization
Before optimization
After optimization
The code is confusing, and functions with the same function appear repeatedly in multiple places. If you need to modify the implementation, you need to find all the places. Modularization, extracting public interfaces and organizing them into libraries, with a clear structure, convenient code reuse, and the ability to prevent variable pollution problems.
JavaScript files are not compressed. The size is relatively large. Loading consumes network time and blocks page rendering. JavaScript public library files are compressed using UglifyJS:
● The size is relatively small and the network loading time is optimized.
● Compression confuses the code to a certain extent. Protected code
requires loading multiple separate JavaScript files when used, which increases the number of http requests and reduces performance. Merging and compressing public libraries reduces the size while reducing the number of http requests.
Lack of documentation (allowing subsequent developers to understand existing The function is unclear, which to a certain extent results in the fact that functions with the same function appear repeatedly in multiple places as mentioned above) Each class, function, and attribute in the public library has documentation
● Modularization (class programming): code Clearly and effectively prevent variable pollution problems, code reuse facilitates expansion, etc.;
● JavaScript compression and obfuscation: reduce size, optimize loading time, obfuscate and protect code;
● JavaScript file merging: reduce http request optimization network time-consuming and improve performance;
● Generate documents: Convenient to use public libraries and easy to find interfaces.
Modularization (class programming)
For static classes, JavaScript implementation is relatively simple, and using Object directly is enough; but it takes a lot of work to create instantiated and inheritable classic classes. Because JavaScript is a prototype-based programming language and does not contain the implementation of built-in classes (it has no access control characters, it does not have the keyword class to define a class, it does not support extend or colon for inheritance, it is useless to support virtual functions (virtual, etc.), but we can easily simulate classic classes through JavaScript.
Static classes
According to the characteristics of the baby JS public interface, they do not need to be instantiated, so this method is used for optimization. The following uses PetConfigParser as an example to introduce the implementation:
var PetConfigParser;
if (!PetConfigParser) {
PetConfigParser = {};
}
(function () {
//private variable , function
/**
* All baby configuration dictionaries, with [cate * 10000 + (lvl - 1) * 10 + dex - 1] as key
* @attribute petDic
* @type {Object}
* @private
*/
var petDic = null; //Baby Dictionary
/**
* Build an Object dictionary based on __pet_config, with cate, dex, lvl combination as key
* @method buildPetDic
* @private
* @return {void}
*/
function buildPetDic() {
petDic = new Object() ;
for (var item in __pet_config) {
var 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; }
}
//public interface
/**
* Based on the baby id, read the corresponding baby information in __pet_config
* @method getPetById
* @param {String/int} petId baby id
* @return {Object} pet All static information of the baby, Such as {id: "300003289", lvl: "1", dex: "2", price: "200", life: "2592000", cate: "3", name: "Flying Angel Level 1 Proficient 2", intro:"", skill:"talisman", skill1_prob:"30", skill2_prob:"0"}
*/
if (typeof PetConfigParser.getPetById !== 'function') {
Id = function (petId) {
var pet = ("undefined" == typeof (__pet_config)) ? null : __pet_config["pet_" + petId];
using JavaScript anonymous functions to create private scopes, which can only be accessed internally. To summarize, the above process is divided into the following steps:
1) Define a global variable (var PetConfigParser), pay attention to the difference between the first letter of the variable and ordinary variables;
2) Then create an anonymous function and run it ((function () {/*xxxx*/ })(); ), create local variables and functions inside the anonymous function, which can only be accessed in the current scope;
3) Global variables (var PetConfigParser) can be accessed anywhere To, add a static function to operate PetConfigParser inside the anonymous function.
Usage examples:
$(function () {
DialogManager.show ("#msgBoxTest", "#closeId"); return false;
DialogManager. hide();
’ Constructor method;
● Prototype method;
● Mixed method of constructor + prototype
Constructor method
The constructor is used to initialize the properties and values of the instance object. Any JavaScript function can be used as a constructor, and constructors must be prefixed with the new operator to create new instances.
var Person = function (name) {
this.name = name;
this.sayName = function(){
alert(this.name);
};
}
//Instantiate
var tyler = new Person("tylerzhu");
var saylor = new Person("saylorzhu");
tyler.sayName();
saylor.sayName();
// Check the instance
alert(tyler instanceof Person);
Is the constructor method familiar with traditional object-oriented languages? It's just that the class keyword is replaced with function.
Note: Do not omit new otherwise Person("tylerzhu") //==>undefined. When the constructor is called using the new keyword, the execution context changes from the global object (window) to an empty context that represents the newly generated instance. Therefore, the this key points to the currently created instance. Therefore, when new is omitted and no context switch is performed, name will be searched in the global object. If it is not found, a global variable name will be created and undefined will be returned.
Prototype method
The constructor method is simple, but there is a problem of wasting memory. For example, in the above example, two objects, Tyler and Saylor, are instantiated. On the surface, there seems to be no problem, but in fact, for each instance object, the sayName() method has exactly the same content. Every time an instance is generated, it must be repeated. The content of the application content.
alert(tyler. sayName == saylor. sayName) outputs false! ! !
Every constructor in Javascript has a prototype attribute that points to another object. All properties and methods of this object will be shared by instances of the constructor.
var Person = function (name) {
Person.prototype = name;
Person.prototype.sayName = function(){
alert(this.name);
}
}
//Instantiation
var tyler = new Person("tylerzhu");
var saylor = new Person("saylorzhu");
tyler.sayName();
saylor.sayName();
//Check the instance
alert(tyler instanceof Person);
At this time, the sayName method of the tyler and saylor instances are both at the same memory address (pointing to the prototype object), so the prototype method saves memory.
But looking at the output of tyler.sayName();saylor.sayName();, you will see the problem - they both output "saylorzhu". Because all properties of the prototype are shared, as long as one instance changes, the others will change accordingly, so the instantiated object saylor covers tyler.
Mixed method of constructor + prototype
The constructor method can allocate different memory for each object of the same class, which is very suitable for setting properties when writing classes; but when setting methods, we need to let different objects of the same class share the same memory, write The best method is to use a prototype. Therefore, when writing a class, you need to mix the constructor method and the prototype method (the methods for creating classes provided by many class libraries or the class writing method of the framework are essentially: constructor + prototype).
var Person = function (name) {
Person.prototype = name;
Person.prototype.sayName = function(){
alert(this.name);
}
}
//Instantiation
var tyler = new Person("tylerzhu");
var saylor = new Person("saylorzhu");
tyler.sayName();
saylor.sayName();
/ /Check the instance
alert(tyler instanceof Person);
In this way, people with different names can be constructed through the constructor, and the object instances also share the sayName method, which will not cause memory waste.
JavaScript compression/merging
The meaning of JavaScript code compression and obfuscation: Simply put, it is to reduce the size of js files, remove redundant comments, line breaks and indentations, etc., making downloading faster and improving user experience.
There are many JavaScript compression tools. I recommend using UglifyJS, the tool currently used by jQuery (jQuery has also used various compression tools before, such as Packer), because its compression performance is very good.
“When jQuery 1.5 was released, john resig said that the code optimizer used was switched from Google Closure to UglifyJS, and the compression effect of the new tool was very satisfactory”