Javascript optimization skills (file slimming)_javascript skills
Recently I have been studying Javascript related technologies. There is a chapter in "Javascript Advanced Programming" that focuses on the importance of optimizing Javascript code. I believe that there are many Javascript developers who will be more or less exposed to such problems while developing.
In most cases, code optimization is not the part that needs to be focused on in actual development. But once the code is completed, developers always expect their code to be as short and efficient as possible. Combining the knowledge gained from the book and my experience in the actual development process, the following explains some of the tricks I have adopted (it can be regarded as following the script).
Foreword
Compared with scripting languages, compiled languages do not need to worry too much about optimization issues. To a large extent, the compiler will perform optimization operations at compile time. For example, all variables, functions, objects, etc. will be replaced with symbols and pointers that only the processor can understand (usually referred to as executable files). Other scripting languages do not need to worry too much about file size, but Javascript is different.
Because it first downloads the source code from the server side, and then executes it by the client's browser. Therefore, the speed of Javascript code is split into two parts: download time (depending on the size of the file) and execution speed (depending on the code algorithm). This article mainly discusses the optimization of Javascript download time, that is, how to reduce the size of the Javascript file itself as much as possible.
One number to keep in mind here is 1160, which is the number of bytes that can fit into a single TCP/IP packet. Therefore, the best expectation is to keep each Javascript file under 1160 bytes for optimal download time.
Delete comment
This seems like nonsense, but many developers forget it. In an actual production environment, comments in scripts should be removed. Comments are very important during development as they help the team understand the code. However, in an actual production environment, comments will significantly increase the size of the script file. Deleting them will not have any impact on the actual execution of the script.
Remove tabs and spaces
Code with good indentation and whitespace is generally good readability. But browsers don't need these extra tabs and spaces, so it's best to remove them. Of course, don't forget the spaces between function parameters, assignment statements, and comparison operations. for example
function showMeTheMoney(money)
{
if (!money) {
return false;
} else {
…
}
} can be optimized into
function showMeTheMoney(money){if(!money){reutrn false;}else{...}}
This can reduce some capacity.
Remove all line breaks
There is a lot of thought about the existence of line breaks in Javascript, but the bottom line is that line breaks increase the readability of the code. However, excessive line breaks will also increase the code size.
There may be some reason why the newlines cannot be removed, so make sure the file is in Unix format. Because the newline character in Windows and Mac formats uses two characters to represent a newline; Unix only uses one. So converting the file to Unix format can also save some bytes.
Replace variable name
This is probably the most boring way to do it, and it's not usually done by hand. After all, variable names are meaningless to the interpreter (just more friendly to developers), and replacing descriptive variable names with simpler, shorter names can also reduce some size in a production environment. For example, the above code can be reduced to:
function sm(m){if(!m){reutrn false;}else{...}}
Although this may seem like a headache, the actual effect is the same.
Use tools
There may be some difficulties in actually using the above method. Fortunately, there are ready-made external tools that can complete these steps. Here are a few brief introductions:
ECMAScript Cruncher: http://saltstorm.net/depo/esc/
JSMin (The JavaScript Minifier): http://www.crockford.com/javascript/jsmin.html
Online JavaScript Compressor.: http://dean.edwards.name/packer/
I guess you will be interested in reading this article.
Other methods
Replace Boolean value
For comparison, true is equal to 1 and false is equal to 0. Therefore, the literal true contained in the script can be replaced with 1, and false can be replaced with 0. This saves 3 bytes for true and 4 bytes for false.
Shorten negative detection
There are often statements in the code that test whether a certain value is valid.Most conditional non-judgments are to determine whether a variable is undefined, null or false, for example:
if (myValue != undefined) {
// ...
}
if (myValue != null) {
// ...
}
if (myValue != false) {
// ...
}
Although these are correct, you can also use the logical NOT operator to have the same effect:
if (!myValue) {
// ...
}
Such a replacement can also save some bytes.
Use array and object literals
This is easier to understand. For example, the following two lines are the same:
var myArray = new Array;
var myArray = [];
However, the second line is much shorter than the first line and can be easily understood. Similar is the object declaration:
var myObject = new Object;
var myObject = {};
For example, take the following statement:
var mySite = new Object;
mySite.author = "feelinglucky";
mySite.location = "http://www.gracecode.com";
Writing like this can also be very easy to understand and is much shorter:
var mySite = {author:"feeinglucky", location:"http://www.gracecode.com"};
Okay, that’s it for this issue. As mentioned above, the speed of Javascript code is divided into two parts: download time (depending on the file size) and execution speed (depending on the code algorithm). This time we are discussing the optimization of download time, and we will discuss the optimization of travel speed in the next issue (this seems very technical, doesn’t it).
Homework is assigned below. Maybe you will be interested in knowing how jQuery compresses its 70KB code to about 20KB.

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Chinese version
Chinese version, very easy to use

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool
