"JavaScript Advanced Programming" 22-24 advanced techniques, offline applications and client caching, best practices _ best practices

Source: Internet
Author: User
Tags sessionstorage

The 22nd Chapter Advanced Technique

Advanced functions:

(1) Security type detection

Object.prototype.toString.call (value) = = "[Object array]"; instrumentation array

The ToString () method of object cannot detect the function name of a non-native constructor.

(2) Scope-safe constructors

This is mapped to the Global object window without using the new operator to call the constructor. The workaround for this problem is to create a scoped security constructor.

First, within the constructor, the instanceof person is judged;

(3) Lazy load function

Lazy loading of a branch that represents the execution of a function occurs only once.

(4) Function binding

ECMAScript 5 defines a native bind () method for all functions, further simplifying the operation. Instead of defining the bind () function yourself, you can call this method directly on the function.

(5) Function Corrie

A topic closely related to function binding is the function of Gerty, which is used to create a function that already has one or more parameters set.

Tamper-resistant objects:

The 6th chapter discusses the problem of object attribute, how to set the attributes of [[configurable]], [[writable]] of each property manually. Similarly, ECMAScript 5 also adds several methods through which you can specify the behavior of an object. However, once you have defined an object as tamper-proof, you cannot undo it.

(1) Non-extensible object

Use the Object.preventextensions () method to make an object extensible.

(2) Sealed object

The sealed object is not extensible, and the [[configurable]] attribute of the existing member is set to false. This means that you cannot delete properties and methods.

To seal the object, you can use the Object.seal () method.

(3) Frozen objects

Frozen objects are neither extensible nor sealed, and the [[writable]] attributes of the object data properties are set to false.

Use the Object.freeze () method to freeze the object.

Advanced Timer:

You can think of JavaScript as running on a timeline. In addition to the main JavaScript execution process, there is a code queue that needs to be executed the next time the process is idle.

The way the timer works on the queue is to insert the code into the queue after a certain time has passed.

(1) Repetitive timer

There are two problems: 1. Some intervals are skipped; 2. The interval between code execution for multiple timers may be smaller than expected.

To avoid the two disadvantages of repeating timers for setinterval (), you can use chained settimeout () calls.

(2) Yielding processes

JavaScript that runs in the browser is assigned a certain amount of resources, one of which is the restriction of long-running scripts, and does not allow the code to continue executing if it runs more than a specific time or a specific number of statements.

When you find that a cycle takes up a lot of time, you can use the timer to split the loop, a technique called array chunking, the basic idea is to create a queue for the project to be processed, then use the timer to take out the next item to be processed, and then set up another timer.

(3) Function throttling

Some of the calculations and processing in browsers are much more expensive than others. For example, DOM operations require more memory and CPU time than non-dom interactions. Successive attempts to do too much DOM-related operations may cause the browser to hang or even crash. To circumvent this problem, you can use the timer to throttle the function.

Function throttle (method, context) {

Cleartimeout (Method.tid);

Method.tid = settimeout (function () {

Method.call (context);



Throttling is most commonly used in resize events. As long as the code is executed periodically, throttling should be used.

Custom events:

Events are the most common way to interact with the DOM, but they can also be used in non-dom code-by implementing a custom event. The idea behind custom events is to create an object that manages events, and let other objects listen to those events.

Drag and drop:

The basic concept of drag-and-drop is simple: Create an absolutely positioned element so that it can be moved with the mouse.

(1) Repair and drag function

(2) Adding custom events

23rd Chapter offline application and Client storage

Supporting offline Web application development is another focus of HTML5.

Offline Detection:

HTML5 defines a Navigator.online property, which is true to indicate that the device is able to surf the web, and a value of false indicates that the device is offline.

HTML5 also defines two events: online and offline, both of which are triggered on the Window object.

Application cache:

HTML5 's application cache, or AppCache, is specifically designed to develop offline Web applications. AppCache is a buffer that is separated from the browser's cache. To save data in this cache, you can use a description file (manifest file) to list the resources to download and cache.

To associate a description file with a page, you can specify this file in the manifest property in

The core of the application cache is the Applicationcache object, which has a status attribute that indicates the current state of the application cache, 0 no cache, 1 idle, 2 check, 3 downloads, 4 update complete, 5 obsolete.

The application cache also has a number of related events that indicate a change in its state:

Checking: Triggered when the browser finds updates for the application cache;

Error: Triggered when errors occur while checking for updates or downloading resources;

Noupdate: Triggered when checking the description file to find that the file has not changed;

Downloading: Triggered when downloading application cache resource is started;

Progress: Continuously triggering in the process of file download application caching;

Updateready: The new application cache on the page is downloaded and can be triggered by swapcache () use;

Cached: Triggered when application cache integrity is available.

Applicationcache.update (), checking for updates manually.

Applicationcache.swapcache (), enabling the new application cache.

Data storage:

(1) Cookies

Cookies are, in nature, bound under a specific domain name.

The total number of cookies per domain is limited.

The size of the cookie in the browser is also limited, and most browsers have a length limit of about 4096B.

Once the secure security flag is set, this cookie can only be transmitted through SSL.

It is best to encode with encodeuricomponent () each time you set up cookies.

To circumvent the number of cookies in the browser's single domain, some developers use a concept called a child cookie.

(2) IE user data

(3) Web Storage mechanism

The purpose of WEB storage is to overcome some of the limitations caused by cookies. When data needs to be tightly controlled on the client side, it is not necessary to send data back to the server continuously.

The original Web Storage specification contains the definitions of two objects: Sessionstorage and Globalstorage.

1.Storage Type:

Storage instances are similar to other objects, with the following methods:

Clear (): Deletes all values;

GetItem (name): Gets the corresponding value according to the specified name;

Key (Index): Gets the name of the index position;

RemoveItem (name): Deletes a name-value pair specified by name;

SetItem (name, value): sets a corresponding value for the specified name.

2.sessionStorage objects:

The Sessionstorage object stores data that is specific to a session, that is, the data is kept only until the browser is closed.

The Sessionstorage object should be used primarily for storing small pieces of data for a session, and if it is necessary to store data across sessions, then globalstorage or localstorage is more appropriate.

3.globalStorage objects

The Globalstorage object is not an instance of storage, and the specific globalstorage[' baidu.com ' is. Be sure to specify a domain name when using Globalstorage.

4.localStorage objects

The Localstorage object replaces Globalstorage as a solution for persisting client data in the revised HTML5 specification.

5.storage Event

Any modifications to the storage object will trigger the storage event on the document.

This event object has the following properties: Domain, Key, newvalue, OldValue.

6. Limit

For Localstorage, most desktop browsers set a limit of 5MB per source.

(4) Indexeddb

INDEXEDDB is a database that holds structured data in a browser. Indexeddb's idea is to create a set of APIs that facilitate the storage and reading of JavaScript objects while also supporting queries and searches.

The INDEXEDDB design operation is entirely asynchronous, and almost every INDEXEDDB operation requires you to register onerror or onsuccess event handlers.


1. The database

The biggest feature of INDEXEDDB is using objects to save data, rather than using tables to save data. A INDEXEDDB database is a collection of objects that are located under the same namespace.

Opening the database call Indexdb.open () returns a Idbrequest object on which the onerror and onsuccess event handlers can be added.

2. Object storage space

After you have established a connection to the database, the next step is to use object storage space.

Var store = Db.createobjectstore ("Users", {keypath: "username"});

Call the Add () and put () methods to add and modify data to the object's storage space.

Once you have created the object storage space and added data to it, you are querying the data.

3. The transaction

After stepping through the creation of object storage space, all of the next actions are done through transactions. Call the transaction () method on a Database object to create a transaction. Any time you want to read or modify data, all operations are organized through transactions.

Var transaction = Db.transaction ();

After you have obtained the index of the transaction, you can access specific storage space by using the ObjectStore () method and passing in the name of the storage space. You can then use Get (), add (), put (), delete (), clear () methods.

Because a transaction can complete any number of requests, the transaction object itself has an event handler: OnError and OnComplete.

4. Using cursor query

Use transactions to retrieve a single object directly from a known key. In cases where multiple objects need to be retrieved, you need to create a cursor within a transaction. A cursor is a pointer to a result set.

Call the Opencursor () method on object storage to create cursors.

Var store = db.transaction ("users"). ObjectStore ("users");

Request = Store.opencursor ();

By default, each cursor only initiates one request, and in order to initiate another request, the following method must be called: Continue (Key), advance (count).

5. Key Range

Using cursors is always a little less desirable, because the way to find data through cursors is too limited. The key range is represented by an instance of Idbkeyrange.

When the key range is defined, it is passed to the Opencursor () method to obtain a cursor that conforms to the corresponding constraint conditions.

6. Set Cursor Direction

7. Index

For some data, you may need to specify multiple keys for an object storage space. For example, to save data by User ID and username, you can use the ID as the primary key to create an index for the user name.

To create an index, you first reference the object storage space, and then call the CreateIndex () method.

The index is actually very similar to the object storage space. Invoking the Opencursor () method on the index also creates a new cursor, which, in addition to storing the index key instead of the primary key in the Event.result.key property, is exactly the same as the cursor returned by calling Opencursor () on the object's storage space.

The index can be deleted by invoking the Deleteindex () method on the object storage space and passing in the index name. Because deleting an index does not affect the data in the object's storage space, this operation does not have any callback functions.

8. Concurrency issues

When you first open the database, remember to specify the Onversionchange event handler. This callback function is executed when another tab page of the same source calls Setversion (). The best way to handle this event is to close the database immediately to ensure that the version update is completed successfully.

When calling Setversion (), it is also important to specify the requested Onblocked event handler, which triggers the event handler if you want to update the version of the database but another tab has already opened the database.

9. Limit

INDEXEDDB also has a size limit, and the chrome limit is 5MB.


INDEXEDDB is a structured data storage mechanism similar to SQL database. But its data is not stored in the table, but is stored in the object storage space. When you create an object storage space, you define a key and then you can add data. You can use cursors to query for specific objects in the object's storage space. Indexes are created to increase query speed and are based on specific properties.

24th Chapter Best Practices


(1) What is maintainable code

Understandable: Other people take over without the original developer to explain;

Intuitive: A look on the understanding;

Adaptability: Data changes do not need to rewrite the method;

Scalability: Consider the future expansion of the core functions;

Can be adjusted for trial: easy to locate errors.

(2) Code conventions

1. Readability:

Most are related to code indentation, typically 4 spaces.

The other side of readability is annotation: functions and methods, large sections of code, complex algorithms, hack.

2. Variable and function naming:

Do not take meaningless names, generally follow the following rules: variable names should be nouns, function names should start with a verb, the return of the Boolean value of the function is beginning, logical.

3. Variable type transparency:

Initialization is specified false,-1, "", null, and so on.

Hungarian notation: "O" stands for objects, "s" for Strings, "I" for integers, "f" for floating-point numbers, and "B" for Boolean values.

(3) Loose coupling

As long as a part of the application relies too much on another part, the code is tightly coupled and difficult to maintain.

1. Decoupling Html/javascript:

InnerHTML = '; This is difficult to maintain

2. Decoupling Css/javascript

Element.classname = ' edit '; better than element.style.color= ' red ';

3. Decoupling application logic/event handlers

(4) Programming practice

1. Respect for the ownership of objects

It means you can't change objects that don't belong to you. Obviously, the array and document are not yours.

2. Avoid global variables

Avoid global variables and functions as much as possible.

3. Avoid comparison with null

4. Using Constants


(1) Notice scope

1. Avoid Global lookup

Using global variables and functions is certainly more expensive than local because it involves finding on the scope chain.

It is always true that a global object that can be used more than once in a function is stored as a local variable.

2. Avoid with statement

The WITH statement creates its own scope, thus increasing the length of the scope chain of the code that it executes.

(2) Choose the correct method

1. Avoid unnecessary property lookup

Using variables and arrays is more efficient than accessing properties on an object, which is an O (n) operation.

2. Optimization cycle

Reduced-value iterations, simplified termination conditions, simplified loop body, and test cycle after use.

3. Expand the Cycle

4. Avoidance of double interpretation

There is a double explanatory penalty when JavaScript code wants to parse JavaScript. This occurs when you use the Eval () function, or the function constructor, and a string parameter using settimeout ().

5. Other Considerations for performance

The native method is faster, the switch statement is faster, and the bit operator is faster.

(3) Minimize the number of statements

1. Statements of multiple variables

2. Insert Iteration Value

3. Using Arrays and object literals

(4) Optimizing DOM Interaction

Dom is undoubtedly the slowest part of JavaScript in all aspects.

1. Minimize site Updates

Once you need to access the DOM section that is part of the page that is already displayed, then you are making a live update.

Use document fragments to build the DOM structure:

Var fragment = Document.createdocumentfragment ();

2. Use of innerHTML

There are two ways to create a DOM node on a page: Using DOM methods such as createelement () and AppendChild (), and using innerHTML. Both methods are more efficient for small dom changes. However, for large DOM changes, using innerHTML is much faster than creating the same DOM structure using the standard DOM method.

When you set innerHTML to a value, the background creates an HTML parser, and then uses the internal DOM call to create the DOM structure, not the DOM calls based on JavaScript. Because the internal method is compiled rather than interpreted, execution is much faster.

3. Using Event proxies

4. Note Htmlcollection

Remember, any time you want to access htmlcollection, whether it's a property or a method, it's a query on a document that's expensive, and minimizing the number of accesses to htmlcollection can greatly improve performance.

In the case where the For loop puts Len = Images.length in the initialization condition, the loop defines the local variable.

The following conditions return the Htmlcollection object:

A call to getElementsByTagName () is made;

Gets the childnodes attribute of the element;

Gets the attributes attribute of the element;

Access to special collections such as document.forms, document.images, etc.


(1) Construction process

Merging JS files

(2) Verify

JSLint can find syntax errors in JavaScript code and common coding errors that can uncover potential problems:

Use of eval ();

The use of a variable is not declared;

A semicolon that is omitted;

Improper change of line;

The wrong comma is used;

An omitted parenthesis around the statement;

The break that is omitted from the switch branch statement;

A variable declared repeatedly;

The use of with;

The equal sign used for the error;

Unreachable code;

(3) compression

1. File compression

The compressor generally does the following: Remove the extra white space, delete all annotations, and shorten the variable name.

2.HTTP compression

Counterweight refers to the number of bytes actually transferred from the server to the browser.

An HTTP header that specifies that a file is compressed using a given format is included in the server response, and the browser then looks at the HTTP header to determine if the file has been compressed and then unzip it using the appropriate format.

Remember a little bit of the cost, because the server has to spend time compressing files on each request, and it takes some time to decompress when the browser receives the files. However, the general price is worth it.

Most Web servers, open source or commercial, have some HTTP compression capabilities.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.