search
HomeWeb Front-endJS TutorialJavaScript project optimization summary
JavaScript project optimization summaryNov 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
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
Replace String Characters in JavaScriptReplace String Characters in JavaScriptMar 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

Custom Google Search API Setup TutorialCustom Google Search API Setup TutorialMar 04, 2025 am 01:06 AM

This tutorial shows you how to integrate a custom Google Search API into your blog or website, offering a more refined search experience than standard WordPress theme search functions. It's surprisingly easy! You'll be able to restrict searches to y

Build Your Own AJAX Web ApplicationsBuild Your Own AJAX Web ApplicationsMar 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

Example Colors JSON FileExample Colors JSON FileMar 03, 2025 am 12:35 AM

This article series was rewritten in mid 2017 with up-to-date information and fresh examples. In this JSON example, we will look at how we can store simple values in a file using JSON format. Using the key-value pair notation, we can store any kind

8 Stunning jQuery Page Layout Plugins8 Stunning jQuery Page Layout PluginsMar 06, 2025 am 12:48 AM

Leverage jQuery for Effortless Web Page Layouts: 8 Essential Plugins jQuery simplifies web page layout significantly. This article highlights eight powerful jQuery plugins that streamline the process, particularly useful for manual website creation

What is 'this' in JavaScript?What is 'this' in JavaScript?Mar 04, 2025 am 01:15 AM

Core points This in JavaScript usually refers to an object that "owns" the method, but it depends on how the function is called. When there is no current object, this refers to the global object. In a web browser, it is represented by window. When calling a function, this maintains the global object; but when calling an object constructor or any of its methods, this refers to an instance of the object. You can change the context of this using methods such as call(), apply(), and bind(). These methods call the function using the given this value and parameters. JavaScript is an excellent programming language. A few years ago, this sentence was

Improve Your jQuery Knowledge with the Source ViewerImprove Your jQuery Knowledge with the Source ViewerMar 05, 2025 am 12:54 AM

jQuery is a great JavaScript framework. However, as with any library, sometimes it’s necessary to get under the hood to discover what’s going on. Perhaps it’s because you’re tracing a bug or are just curious about how jQuery achieves a particular UI

10 Mobile Cheat Sheets for Mobile Development10 Mobile Cheat Sheets for Mobile DevelopmentMar 05, 2025 am 12:43 AM

This post compiles helpful cheat sheets, reference guides, quick recipes, and code snippets for Android, Blackberry, and iPhone app development. No developer should be without them! Touch Gesture Reference Guide (PDF) A valuable resource for desig

See all articles

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)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools