Teach you how to write high-performance JavaScript

Recently, I was studying performance optimization again, so I reviewed the notes I had written in the book of High-performance JavaScript three years ago. I felt that although I had written things three years ago, I still felt that they were useless and useful. This paper mainly introduces two major piecesPage level optimization,Code level optimization; As for practice and application and tools, the previous article has explained:Front-end performance optimization and its measurement method

Page level optimization

Page-level optimization – loading and execution

Simplify the page at the design and implementation level

  1. Script location: At the bottom, load the script content after the page information is loaded

    Move the script as far back as possible to minimize the impact on concurrent downloads.

  2. Organizing scripts: reduce external links

    1. The power of caching is powerful, and proper caching Settings can significantly reduce HTTP requests.

      The more you can cache the better, and the longer you can cache the better. Make the resource stay in the cache as long as possible.

      Eg. For image resources that rarely change, you can set a long expiration Header directly by using the Expires in the HTTP Header.

      Resources that change infrequently and are likely to change can use last-modifed for request validation

    2. Resource merging and compression As much as possible, external scripts, styles are combined, many into one.

      CSS, Javascript, Image can be compressed with the corresponding tools, often after compression can save a lot of space

      Recommended tools: grunt, gulp, tool.css-js.com/ (UglifyJS), webpack

    3. CSS Sprites combine CSS images to reduce the number of requests

    4. Inline Images Embed Images into a page or CSS

    5. Lazy Load Images

      Lazy image loading

  3. Non-blocking script: The js code is loaded after the page is loaded. The load time of the Window object is triggered before the script is downloaded

    (1) delayed script: parallel download, will not block as (IE4+ and firefox3.5+) wait for the page to complete

    Async (HTML5 asynchronous loading script) Automatically executes the script after it is loaded

    Eg. Github.com/dingxiaoxue…

    (2) Dynamic script elements:

    With its cross-browser compatibility and ease of use, it has become the most versatile non-blocking loading solution eg. github.com/dingxiaoxue…

    Pay attention to the loading order

    Eg.github.com/dingxiaoxue…

    Since the process is asynchronous, larger files do not matter

    (3) XMLHttpRequest script injection: another way to load scripts without blocking

    Pros: The same set of code works on all browsers, doesn’t execute immediately after downloading and can be delayed until you’re ready

    Disadvantages: Limitation js files must be in the same domain as all requested pages (not suitable for us to download from CDN)

    (4) Non-blocking mode is recommended:

    A. above (2) B. UI3 github.com/yui/yui3/ c. lazyload class library D.labjs

Page level optimization – summary

Managing JavaScript code in the browser is tricky because the execution of the code blocks other processes in the browser, such as user interface drawing. Every time aScript tag is encountered, the page has to stop and wait for the code to download and execute before moving on to other parts. However, there are several ways to reduce js’s impact on performance:

  1. Before the body closes the tag, place all script tags at the bottom of the page. This ensures that the page is rendered before the script is executed
  2. Merge scripts. The fewer script tags in a page, the faster it loads and the faster it responds.
  3. Multiple ways to download JS without blocking: using
 <script defer>
Copy the code

The defer attribute

Dynamically created Script elements are used to download and execute the code

Use the XHR object to download the JS code and inject the page

With these strategies, you can greatly improve the actual performance of web applications that use a lot of JS

Code level optimization

Code level optimization – Data access

  1. Managing scope: (1) Scope chain and identifier resolution

    Calling the same function multiple times will cause multiple execution environments to be created, which will be destroyed after the function is executed

    Having to go through a search process for each identifier during a function call affects performance

    (2) Performance of identifier parsing

    The deeper an identifier is, the slower it is to read and write;

    In a browser with an unoptimized JS engine, it is recommended to use local variables whenever possible

    Store a reference to a global variable in a local variable, and then use the local variable instead of the global variable

    Eg. Github.com/dingxiaoxue…

    (3) Change the scope chain

    With()

    Try{method()}catch(ex){handleError(ex)}

    Eval()

    Avoid using dynamic scope if possible, and use dynamic scope only when necessary

    (4) Closure, scope and memory

    Closures have more memory than non-closures, and IE uses non-native JS objects to implement DOM objects, which can cause memory leaks

    When cross-scoped identifiers are accessed frequently, there is a performance penalty per access

    Recommendations across scopes to mitigate the impact of closures on execution speed

    Store commonly used cross-scope variables in local variables, and then access the local variables directly

  2. Object members (properties and methods

    HasOwnProperty () determines whether an object contains a particular instance member

    In Determines whether an object contains specific properties (search instance and stereotype)

    (2) Prototype chains

    Reduced scope chain lookups

    The deeper the object is in the prototype chain, the slower it is to find it

    (3) Each time the nested member encounters the point operator, the nested member causes the JS search engine to search all object members

    The deeper the object members are nested, the slower the reading

    The Location. The href fastest

    Window.location.href

    Window. The loacation. Href. ToString () the slowest

    (4) Cache object member values

    Do not look for the same object member more than once in the same function unless its value has changed

  1. The deeper a property or method is in the prototype chain, the slower it is to access it

    Literals: they represent themselves and are not stored in a specific location.

    String, number, Boolean, object, array, function, regular expression, null, undefined

    Local variable: A data storage unit defined by the developer using the keyword var

    Array elements: Stored inside JavaScript array objects and indexed by numbers

    Object members: Stored inside JavaScript objects, indexed by strings

    The amount of time it takes for each browser to perform 200,000 operations on the four data storage locations

    Summary data access

    In JavaScript, where data is stored can have a significant impact on the overall performance of the code.

    There are four ways to store data: literals, variables, array entries, and object members.

    1. Accessing literals and local variables is the fastest, while accessing array elements and object members is relatively slow

    2. Access to local variables is faster than access to cross-scope variables because local variables exist at their actual location in the scope chain

      The deeper the variable is in the scope, the longer it takes to access it.

      Because global variables are always at the end of the scope, they are also the slowest to access

    3. Avoid using the with statement because it changes the execution environment scope chain. The catch clause in a try-catch statement has the same effect and should be used with care

    4. Nested object members can significantly affect performance and should be used sparingly

    5. The deeper a property or method is in the prototype chain, the slower it is to access it

    6. In general, you can improve JavaScript performance by storing common object members, array elements, and cross-domain variables in local variables, because local variables are faster a. More than one access to any object property

      B. Access any array member more than one time

    With these strategies, you can significantly improve the actual performance of Web applications that use a lot of variable JavaScript

Code level optimization -DOM programming

Code level optimization -DOM access and modification

DOM access and modification

Minimize DOM access times and try to handle them on the JS side as much as possible.

If you need to access a DOM node multiple times, use local variables to store references to it.

The more times you access the DOM, the slower your code will run

Minimize DOM access and keep operations on the ECMAScript side as much as possible

Eg.github.com/dingxiaoxue…

  1. InnerHTML compares the DOM method document.creatElement() to innerHTML

    InnerHTML is faster for all browsers except the WebKit kernel (Chrome and Safari)

    Eg. Github.com/dingxiaoxue…

    Eg. Github.com/dingxiaoxue…

    Compare using innerHTML and DOM methods to create a 1000 row table; In IE6, innerHTML is more than three times faster, whereas in the new WebKit browser innerHTML is slower.

  2. Node clone (slightly faster) Clone existing elements — Use element.clonenode () instead of Document.creatElement ()

    Eg.github.com/dingxiaoxue…

  3. HTML Collection The HTML collection is handled with care because it connects to the underlying document in real time. Cache the length of the collection in a variable and use it in the iteration. If the collection needs to be manipulated frequently, it is recommended to copy it into an array.

(1) Expensive collections Traversing an array is significantly faster than traversing an HTML collection for the same content and amount

Optimization: Cache the length of the collection in a local variable and then use that variable in the conditional exit statement of the loop

Eg. Github.com/dingxiaoxue…

ToArray () collection toArray function

(2) Use local variables when accessing the collection

Using local variables to store collection references and collection elements in a loop is faster

Eg. Github.com/dingxiaoxue…

  1. If possible, use a faster API to traverse the DOM.
GetElementById () getElementsByTagName() querySelectorAll() querySelectorAll() eg.elements = document.querySelectorAll('#menu a'); var elements = document.getElementById('menu').getElementsByTagName('a'); var errs = document.querySelectorAll('div.warning, div.notice');Copy the code

(1) Obtain DOM elements

ChildNodes VS nextSilbing (nextSiblings are 7 times 105 times faster, 6 times 16 times faster)

Eg.github.com/dingxiaoxue…

(2) Element nodes

Children is faster than childNodes on all browsers (1.5-3 times)

The speed of traversing the children collection in IE is obviously faster than traversing childNode (IE6 24 times, IE7 124 times).

Eg.github.com/dingxiaoxue…

(3) Selector API

Code level optimization – redraw and rearrange

When the browser has downloaded all of the page’s HTML tags, JavaScript, CSS, and images, it parses the file and creates two internal data structures:

Tree: represents the page structure (which needs to be reformatted when the layout and geometry change)

A rendering tree: how do DOM nodes display

1. When the rearrangement will happen

(1) Add or remove visible DOM elements

(2) Change of element position

(3) Element size changes (because margin, fill, border width, width, height, etc.)

(4) Content changes, for example, text changes or an image is replaced by another of a different size

(5) Initial page rendering

(6) The browser window is resized

Depending on the nature of the change, either large or small portions of the rendered tree need to be recalculated. Some changes can cause an entire page to be reformatted: for example, when a scrollbar appears.

Retrieving layout information will result in a refresh queue action. It is best not to use the following properties:

• scrollTop, scrollLeft, scrollWidth, scrollHeight • clientTop, ClientLeft, clientWidth, clientHeight • getComputedStyle()(currentStylein IE)

2. Minimize redraws and rearrangements

When changing styles in batches, manipulate the DOM tree “offline,” use caching, and reduce the number of times you access layout information

(1) Change the style

(2) Modify the DOM in batches

When you need to make multiple changes to a DOM element, you can reduce the number of redraws and relayouts by following these steps:

Removes the element from the document flow

Apply multiple changes to it

Element is brought back to the document

There are three basic ways to remove the DOM from a document:

Hide the element, modify it, and then display it

Use a document fragment to create a subtree outside of the existing DOM, and then copy it into the document.

Copy the original element to a detached node, modify the copy, and then overwrite the original element.

3. Take the element out of the animation stream

Use absolute coordinates to position the elements of the page animation outside of the page layout flow.

Start element animation. As it expands, it temporarily covers part of the page. This is a redrawing process, but only affects a small part of the page, avoiding retypesetting and redrawing a large page.

When the animation ends, reposition so that the rest of the document is moved down only once.

4. Event delegation

Use event delegates to reduce the number of event handlers

5. How to hover

Code level optimization – algorithm and process control

The overall structure of the code is one of the main factors affecting the speed of the operation.

The organization of your code and the way you solve specific problems are the main factors that affect your code’s performance.

  1. In most languages, loops are where most of the code execution time is spent.

    Infinite or long running loops can seriously affect the user experience.

    Cycle types (4)

    For(){// loop body}

    While(){(){// loop body}

    Do{{// loop body}while();

    For(var prop in object){// loop body};

    Cycle performance

    The source of the ongoing debate over cycle performance is the choice of cycle types.

    The for-in loop in Js is noticeably slower than the other three, and the other three are not much different

    Iterating over an object whose properties are unknown — for-in (don’t use for-in to iterate over group members)

    Traversing a limited list of known properties — 1/2/3 (loop type selected based on requirements, not performance)

    A. Handle transactions in each iteration

    B. Number of iterations

    By reducing the time cost of one or both of A and B, you improve the overall performance of the loop.

    Reduce the iteration effort

    Limit the number of time-consuming operations in a loop

    It is important to note that javascript does not have block-level scope, only function-level scope, which means that the var statement in the for loop initialization creates a function-level variable rather than a looping level variable

    The ways to optimize the loop are as follows

    1, reduce the number of times to find object members and array items (use local variables to store object members to find)

    2. Invert the array order to improve loop performance, i.e. start with the last item and proceed forward

     for (var i = arr.length-1; i >= 0 ; i--) {
                //process
            }
    Copy the code

    3. If possible, you will use a for loop instead of jQuery’s each method to iterate through the array. That’s because jQuery’s each method is based on function iteration. Although function-based iteration provides a more convenient method of iteration, it is much slower than looping based iteration.

    4. Sometimes we wonder whether to use an if-else or a switch. In fact, the switch runs faster than the if-else in most cases, so the switch statement is a better choice when judging more than two discrete values

    5. The easiest way to optimize if-else is to make sure that the most likely condition occurs first. Another way is to optimize the number of times the condition is judged

 if (value == 0) {
   return result0;
 } else if (value == 1) {
   return result1;
 } else if (value == 2) {
   return result2;
 } else if (value == 3) {
   return result3;
 } else if (value == 4) {
   return result4;
 } else if (value == 5) {
   return result5;
 } else if (value == 6) {
   return result6;
 } else if (value == 7) {
   return result7;
 } else if (value == 8) {
   return result8;
 } else if (value == 9) {
   return result9;
 } else if (value == 10) {
   return result10;
 }
Copy the code

The following method optimizes the above example by using binary search to divide the range into a series of intervals and then gradually narrowing the range

if (value < 6) { if (value < 3) { if (value == 0) { return result0; } else if (value == 1) { return result1; } else { return result2; } } else { if (value == 3) { return result3; } else if (value == 4) { return result4; } else { return result5; } } } else { if (value < 8) { if (value == 6) { return result06; } else if (value == 7) { return result7; } } else { if (value == 8) { return result8; } else if (value == 9) { return result9; } else { return result10; }}}Copy the code

6. Using recursion can simplify complex algorithms, but recursive functions run for a long time if their terminating conditions are unclear or absent. So recursive functions can also run into the browser’s “call stack size limit.”

Using optimized loops instead of long-running recursive functions can improve performance because running a loop is much less expensive than calling a function repeatedly

If there is too much recycled data, consider using the duff equipment principles described below to improve performance

  1. Damien duff equipment

var iterations = Math.floor(items.length / 8), startAt = items.length % 8, i = 0; Process switch (startAt) {case 0: process(items[i++]); case 7: process(items[i++]); case 6: process(items[i++]); case 5: process(items[i++]); case 4: process(items[i++]); case 3: process(items[i++]); case 2: process(items[i++]); case 1: process(items[i++]); } startAt = 0; } while (--iterations); ` ` ` 2.Copy the code
var i = items.length % 8; while (i) { process(items[i--]); } i = Math.floor(items.length / 8); while (i) { process(items[i--]); process(items[i--]); process(items[i--]); process(items[i--]); process(items[i--]); process(items[i--]); process(items[i--]); process(items[i--]); } ` ` `Copy the code
  1. Memoization

    Avoiding repetition is the core idea of Memoization, which caches the results of previous calculations for later use. The following code calculates factorials using the idea of caching results

function memFactorial(n) { if (! memFactorial.cache) { memFactorial.cache = { "0": 1, "1": 1 }; } if (! memFactorial.cache.hasOwnProperty(n)) { memFactorial.cache[n] = n * memFactorial(n - 1); } return memFactorial.cache[n]; }Copy the code

The general method is written in the following code:

function memoize(fundamental, cache) { cache = cache || {}; var shell = function (arg) { if (! cache.hasOwnProperty(arg)) { cache[arg] = fundamental(arg); } return cache[arg]; } return shell; Function factorial(n) {if (n==0) {return 1; }else{ return n*factorial(n-1); } } var memfactorial = memoize(factorial, { "0": 1, "1": 1 }); memfactorial(6);Copy the code
  1. Algorithm and process control summary

    1. Of the four loops (for, for-in, while, do-while), only the for-in loop is significantly slower than the others, and the other three have little difference in speed
    2. Do not use for-in loops unless you are iterating over an object whose properties are unknown
    3. The best way to improve cycle performance is to reduce the amount of computation in each iteration and reduce the number of cycle iterations
    4. In general, switch is always faster than if-else, but not always the best solution; Table lookup is faster than if-else or switch when there are multiple criteria
    5. The size of the browser call stack limits the application of the ground cabinet algorithm in JavaScript; Stack overflow error causes other code to not execute properly; If you encounter a stack overflow error, change the method to an iterative algorithm or use tabulation to avoid rework

Code level optimization – Strings and regular expressions

str += "one" + "two"; // The following code adds two lines of content directly to STR to avoid creating temporary strings by 10% to 40%. str += "one"; str += "two"; STR = STR + "one" + "two"; STR = STR + "one" + "two"; // In fact, STR = STR + "one" + "two"; Equivalent to STR = ((STR + "one") + "two");Copy the code

The array.prototype. join method that combines all elements of an Array into a single string may be popular. Although it was the only efficient way to combine large numbers of strings in IE7 and earlier, Array item concatenation is actually slower than other string concatenation methods in most modern browsers.

In most cases, using concat is slightly slower than using simple + and +=.

Array union is one of the slowest ways to concatenate strings when concatenating a large number or size of strings. Use simple + and += instead to avoid unnecessary intermediate strings

Code level optimization – responsive user interface

Code level optimization – Data transfer Ajax

The data transfer

There are five common techniques for requesting data from a server:

  1. XMLHttpRquest(XHR)
  2. Dynamic Script Tag insertion
  3. iframes
  4. Comet (a hack)
  5. Multipart XHR

The three techniques used in modern high-performance JavaScript are XHR, dynamic script tag insertion, and multipart XHR. Using Comet and iframe (as a data transfer technology) is often a limiting case and will not be discussed here.

1.XMLHttpRquest: Allows asynchronous sending and receiving data, can add any header information and parameters in the request, and read all the header information and response text returned by the server

When using XHR, the comparison between POST and GET should be used for requests that do not change the server state and only fetch data (this is called idempotent behavior). The data requested by GET is cached, which can improve performance if the same data needs to be requested multiple times.

Only when the length of the requested URL plus parameters is close to or more than 2048 characters, you should use POST to obtain data. This is because Internet Explorer limits the URL length. If the URL length is too long, the requested URL will be truncated

Another note: since the response message is the source code for the script tag, the data returned must be executable javascript code, so you can’t use pure XML, pure JSON, or any other format of data, either of which must be wrapped in a callback function

When sending data to the server using XHR, GET is faster because, for small amounts of data, a GET request sends only one packet to the server, whereas a POST request sends at least two packets, one loaded with the header and the other loaded with the POST body. POST is better suited for sending large amounts of data to the server

Dynamic Script Tag insertion solves one of XHR’s biggest limitations: it can retrieve data from servers in different domains, at the insertion line. This is a hacking technique. Instead of instantiating a dedicated object, you create a new script tag in JavaScript and set its source property to a URL pointing to a different domain

var scriptElement = document.createElement('script');
scriptElement.src = 'http://any-domain.com/javascript/lib.js';
document.getElementsByTagName_r('head')[0].appendChild(scriptElement);
Copy the code

But dynamic script tag insertion provides less control than XHR. You cannot send headers by request. Arguments can only be passed through the GET method, not POST. You can’t set a timeout or retry for the request, and in fact, you don’t need to know if it failed. You have to wait for all the data to return before you can access it. You cannot access the response header or the entire response as a string.

This last point is very important. Because the response message is used as source code for the script tag, it must be executable JavaScript. You can’t use bare XML, or bare JSON, any data, no matter what format, must be assembled in a callback function.

 var scriptElement = document.createElement('script');
   scriptElement.src = 'http://any-domain.com/javascript/lib.js';
   document.getElementsByTagName_r('head')[0].appendChild(scriptElement);
   function jsonCallback(jsonString) {
      var data = ('(' + jsonString + ')');
   }
Copy the code

In this example, the lib.js file will call the jsonCallback function to assemble the data:

jsonCallback({ "status": 1, "colors": [ "#fff", "#000", "#ff0000" ] });
Copy the code

Despite these limitations, the technology is still very fast. The response is to run JavaScript instead of being a string that must be processed further. Because of this, it is probably the fastest way to retrieve and parse data on the client side. We compare the performance of dynamic script tag insertion with XHR, in the JSON section later in this chapter.

Be careful using this technique to request data from servers you do not directly control. JavaScript has no concept of permissions or access control, so any code inserted on your page using dynamic script tags has complete control over the entire page. This includes modifying any content, redirecting users to another site, or tracking what they do on the page and sending the data to third parties. Be very careful when using code from external sources.

3.3.com ET A hack: Web applications represented by instant messaging have Low Latency requirements for data, which can no longer be satisfied by the traditional polling method, and will also bring bad user experience. Thus a “server push” technique based on HTTP persistent connections was hacked. This technique is known as Comet, a term coined by Alex Russell, project lead for the Dojo Toolkit, in his blog Post Comet: Low Latency Data for the Browser.

In fact, server push has been around for a long time and is widely used in the classic Client/Server model, but browsers are too lazy to support this technology. But the advent of Ajax made it possible to implement this technology in the browser, and Google’s integration of Gmail and GTalk was the first to use it. With some key issues resolved (such as IE’s loading display issues), the technology quickly gained acceptance, and there are now a number of mature open source Comet frameworks.

Here’s a simple comparison between a typical Ajax and Comet data transfer. Typical Ajax communication is also a classic use of the HTTP protocol, in order to get data, you must first send a request. In web applications with high Low Latency requirements, you can only increase the frequency of server requests. Comet is different, the client and the server to maintain a long connection, only the client needs the data update, the server will take the initiative to push the data to the client.

Comet can be implemented in two main ways:

[1] Ajax-based long-polling method

The browser sends

[2] HTTP streaming based on Iframe and HTMLfile

The Iframe is an HTML tag whose SRC attribute keeps a persistent connection request to the specified server. The server can return data over and over again, which is closer to the traditional server approach than the first method.

In the first approach, the browser calls the JS callback directly after receiving the data, but how does this approach respond to the data? You can embed JS scripts in the returned data, such as “”. The server side takes the returned data as the parameter of the callback function, and the browser will execute this JS script after receiving the data.

However, this approach has one obvious disadvantage: the progress bar at the bottom of Both IE and Morzilla Firefox shows that the loading is incomplete, and the icon above IE rotates constantly to indicate that the loading is in progress. The geniuses at Google solved the loading display problem in Internet Explorer with an ActiveX called “HTMLFile” and applied it to gmail+ GTalk products.

5. Multipart XHR: Allows a client to send multiple resources from the server to the client with a single HTTP request by packaging the resource on the server as a long string separated by a mutually agreed upon string and sending it to the client, and then processing that long string in javaScript. Each resource is resolved based on the MIme-type type and other incoming headers

Multipart XHR uses streams. By listening for readyState of 3, we can fragment a large response before it is fully accepted, so we can process the response fragments in real time. This is the main reason why MXHR can improve performance so much

Disadvantages of using Multipart XHR (but it can significantly improve overall page performance) :

  1. The obtained resource cannot be cached by the browser
  2. Older versions of IE do not support readyState 3 and data: URLS (images are not converted from base64 strings to binary, but are created using data: URLS, And specify the mime-type to be image/jpeg and use readyState to be 3 because you can’t wait for all the data to be transferred, that would be very slow)

Beacons technology

Use javascript to create a new Image object, and set the SRC attribute to the URL of the script on the server. This URL contains the key-value pair data we want to return through GET (no IMG element is created, and no DOM is inserted). The server receives the data and saves it. It sends any feedback to the client. This is the most efficient way to send information back to the server, and while it has the advantage of a low performance cost, it also has the obvious disadvantage

The length limit for sending data is fairly small

One way to receive data from the server is to listen for the load event on the Image object. Another way is to check the width and height of the Image returned by the server to determine the status of the server

The data format

XML is now a data format that has been completely replaced by JSON for a number of reasons, mainly because XML files are too large and slow to parse, and XPath is not widely supported even though it is much faster than getElementsByTagName in parsing XML documents

Compared with XML, JSON has less file size and strong versatility

JSON data is treated as another JavaScript file and executed as native code, and for this to happen, the data must be wrapped in a callback function called JSON with padding json-p

The fastest JSON format is json-p in the form of an array

Security considerations must be taken with json-p because json-p must be executable JavaScript, which can be called by anyone and inserted into the site using dynamic script injection techniques. On the other hand, JSON is invalid JavaScript before eval. With XHR it is just fetched as a string, so don’t encode any sensitive data in Json-p.

Ideal data format should be only contain the necessary structure, so that you can break down each separate fields, so the custom format is relatively smaller, can quickly download, and easy to parse (split function can be used as long as), so when you create a custom format, one of the most important decision is what the separator

var rows = req.responseText.split(/\u0001/); Var rows = req.responsetext.split ("\u0001"); // String as separator (safer)Copy the code

Data Format Summary

In general, the lighter the format, the better, preferably JSON and a custom format delimited by strings. If the data set is large or parsing time is an issue, use one of these two formats;

JSON_P data, obtained using dynamic script tag insertion. It treats data like runnable JavaScript rather than strings and parses extremely fast. It can also be used across domains, but should not involve sensitive data

Custom format of character split, extracted using XHR or dynamic script tag insertion techniques, resolved using split(). This technique is slightly faster than the JSON_P technique for parsing very large data sets and generally has smaller file sizes.

Cache data

  • On the server, set the HTTP header to ensure that your response is cached by the browser
  • On the client side, the obtained information is stored locally to avoid further requests

If you want the Ajax response to be cached by the browser, you must use GET to make the request. Setting the Expires header is the easiest way to ensure that the browser caches the Ajax response across pages and sessions

Of course, you can also manually manage the local cache, that is, directly cache the data received by the server

You get used to Ajax libraries, and you don’t even know how to write an XMLHttpRequest. In fact, many Ajax libraries have limitations (such as not allowing you to directly access the ReadyStatechange event, This also means that you have to wait for the full response to be received before you can start using it) so……

Programming practice

Build and deploy high-performance JavaScript applications

tool

In this paper, the demo

Github.com/dingxiaoxue…

Front-end work up [1] front-end work up [1] scan code attention xiaoyuanlianer666

Small round face: public number: small round face (Xiaoyuanlianer666), gold: small round face.