Home Web Front-end JS Tutorial JavaScript project optimization summary

JavaScript project optimization summary

Nov 26, 2016 pm 04:19 PM
JavaScript

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”


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Replace String Characters in JavaScript Replace String Characters in JavaScript Mar 11, 2025 am 12:07 AM

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

Build Your Own AJAX Web Applications Build Your Own AJAX Web Applications Mar 09, 2025 am 12:11 AM

So here you are, ready to learn all about this thing called AJAX. But, what exactly is it? The term AJAX refers to a loose grouping of technologies that are used to create dynamic, interactive web content. The term AJAX, originally coined by Jesse J

10 jQuery Fun and Games Plugins 10 jQuery Fun and Games Plugins Mar 08, 2025 am 12:42 AM

10 fun jQuery game plugins to make your website more attractive and enhance user stickiness! While Flash is still the best software for developing casual web games, jQuery can also create surprising effects, and while not comparable to pure action Flash games, in some cases you can also have unexpected fun in your browser. jQuery tic toe game The "Hello world" of game programming now has a jQuery version. Source code jQuery Crazy Word Composition Game This is a fill-in-the-blank game, and it can produce some weird results due to not knowing the context of the word. Source code jQuery mine sweeping game

jQuery Parallax Tutorial - Animated Header Background jQuery Parallax Tutorial - Animated Header Background Mar 08, 2025 am 12:39 AM

This tutorial demonstrates how to create a captivating parallax background effect using jQuery. We'll build a header banner with layered images that create a stunning visual depth. The updated plugin works with jQuery 1.6.4 and later. Download the

How do I create and publish my own JavaScript libraries? How do I create and publish my own JavaScript libraries? Mar 18, 2025 pm 03:12 PM

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

How do I optimize JavaScript code for performance in the browser? How do I optimize JavaScript code for performance in the browser? Mar 18, 2025 pm 03:14 PM

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

Auto Refresh Div Content Using jQuery and AJAX Auto Refresh Div Content Using jQuery and AJAX Mar 08, 2025 am 12:58 AM

This article demonstrates how to automatically refresh a div's content every 5 seconds using jQuery and AJAX. The example fetches and displays the latest blog posts from an RSS feed, along with the last refresh timestamp. A loading image is optiona

Getting Started With Matter.js: Introduction Getting Started With Matter.js: Introduction Mar 08, 2025 am 12:53 AM

Matter.js is a 2D rigid body physics engine written in JavaScript. This library can help you easily simulate 2D physics in your browser. It provides many features, such as the ability to create rigid bodies and assign physical properties such as mass, area, or density. You can also simulate different types of collisions and forces, such as gravity friction. Matter.js supports all mainstream browsers. Additionally, it is suitable for mobile devices as it detects touches and is responsive. All of these features make it worth your time to learn how to use the engine, as this makes it easy to create a physics-based 2D game or simulation. In this tutorial, I will cover the basics of this library, including its installation and usage, and provide a

See all articles