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.

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Win11 Tips Sharing: One trick to skip Microsoft account login Windows 11 is the latest operating system launched by Microsoft, with a new design style and many practical functions. However, for some users, having to log in to their Microsoft account every time they boot up the system can be a bit annoying. If you are one of them, you might as well try the following tips, which will allow you to skip logging in with a Microsoft account and enter the desktop interface directly. First, we need to create a local account in the system to log in instead of a Microsoft account. The advantage of doing this is

In C language, it represents a pointer, which stores the address of other variables; & represents the address operator, which returns the memory address of a variable. Tips for using pointers include defining pointers, dereferencing pointers, and ensuring that pointers point to valid addresses; tips for using address operators & include obtaining variable addresses, and returning the address of the first element of the array when obtaining the address of an array element. A practical example demonstrating the use of pointer and address operators to reverse a string.

Time complexity measures the execution time of an algorithm relative to the size of the input. Tips for reducing the time complexity of C++ programs include: choosing appropriate containers (such as vector, list) to optimize data storage and management. Utilize efficient algorithms such as quick sort to reduce computation time. Eliminate multiple operations to reduce double counting. Use conditional branches to avoid unnecessary calculations. Optimize linear search by using faster algorithms such as binary search.

VSCode (Visual Studio Code) is an open source code editor developed by Microsoft. It has powerful functions and rich plug-in support, making it one of the preferred tools for developers. This article will provide an introductory guide for beginners to help them quickly master the skills of using VSCode. In this article, we will introduce how to install VSCode, basic editing operations, shortcut keys, plug-in installation, etc., and provide readers with specific code examples. 1. Install VSCode first, we need

Title: PHP Programming Tips: How to Jump to a Web Page within 3 Seconds In web development, we often encounter situations where we need to automatically jump to another page within a certain period of time. This article will introduce how to use PHP to implement programming techniques to jump to a page within 3 seconds, and provide specific code examples. First of all, the basic principle of page jump is realized through the Location field in the HTTP response header. By setting this field, the browser can automatically jump to the specified page. Below is a simple example demonstrating how to use P

Win11 tricks revealed: How to bypass Microsoft account login Recently, Microsoft launched a new operating system Windows11, which has attracted widespread attention. Compared with previous versions, Windows 11 has made many new adjustments in terms of interface design and functional improvements, but it has also caused some controversy. The most eye-catching point is that it forces users to log in to the system with a Microsoft account. For some users, they may be more accustomed to logging in with a local account and are unwilling to bind their personal information to a Microsoft account.

In Go language program development, function reconstruction skills are a very important part. By optimizing and refactoring functions, you can not only improve code quality and maintainability, but also improve program performance and readability. This article will delve into the function reconstruction techniques in the Go language, combined with specific code examples, to help readers better understand and apply these techniques. 1. Code example 1: Extract duplicate code fragments. In actual development, we often encounter reused code fragments. At this time, we can consider extracting the repeated code as an independent function to

1. Press the key combination (win key + R) on the desktop to open the run window, then enter [regedit] and press Enter to confirm. 2. After opening the Registry Editor, we click to expand [HKEY_CURRENT_USERSoftwareMicrosoftWindowsCurrentVersionExplorer], and then see if there is a Serialize item in the directory. If not, we can right-click Explorer, create a new item, and name it Serialize. 3. Then click Serialize, then right-click the blank space in the right pane, create a new DWORD (32) bit value, and name it Star
