1. Reduce the number of HTTP requests and the size of transmitted packets

  • CSS SPRITE technology
  • Use vector graphics such as ICON FONT or SVG + to reduce the number of HTTP requests or reduce the size of the requested content + render faster: For bitmaps (PNG/JPG/GIF), you need to encode the image before rendering + not easy to distort + you can also use webP format, which is smaller (but requires server-side support for this format of request processing).
  • Lazy image loading (lazy loading) technology + when the page is loaded for the first time, it does not request real images to improve the speed of the first rendering page + When the page is loaded, the images that appear in the user’s field of view are loaded for real, and the ones that do not appear are not loaded first (save traffic, We also load data in batches as much as possible (do not request too much data at once, such as paging).
  • Cancel preload of audio and video files (preload=’none’) to speed up the first rendering of the page and load them when they need to be played
  • The data transfer between the client and server is done as much as possible in the JSON format, and the XML format is larger than the JSON format (it can also be based on binary encoding or stream format, which is much better than file transfer).
  • The page of CSS/JS/ images and other files to merge compression + merge: strive for CSS and JS only import one (Webpack can achieve automatic compression) + compression: based on WebPack can be compressed, for the image of their own tools to find the first compression, you can also use the server GZIP compression
  • Image map: For images used multiple times (especially background images), we try to extract them into a common style rather than resetting the background every time
  • Image BASE64 (Use BASE64 code to represent the image, reduce HTTP requests, increase browser rendering speed, so in real projects, especially mobile, if the image loading slow, maybe BASE64; However, BASE64 causes super nasty code in files and is not good for maintenance and development, so use it sparingly; Webpack can configure images in BASE64;)

2. Set various caching, preprocessing, and persistent connection mechanisms

  • Cache static resources that do not change frequently (usually 304 or ETAG negotiated cache)
  • Create a strong Cache for cache-Control and Expires HTTP
  • DNS cache or DNS PREFETCH to reduce DNS lookups
  • Set the local offline storage (MANIFEST) or do some infrequently changed data local storage (Webstorage, IndexDB)
  • Do a CDN (regional distributed server) if you have money, and there is a deep pockets way: add servers
  • Set up Connection:keep-alive TCP long Connection
  • Using the HTTP2 version of the protocol (now generally used HTTP1.1) + can coexist with multiple TCP channels => pipelinedlink + think: HTTP VS HTTPS + think: HTTP1 VS HTTP2
  • A project is divided into different domains (different servers), such as resource WEB server, data server, picture server, video server, etc. In this way, server resources are properly utilized, but excessive DNS resolution is caused

3. Performance optimization for code

  • Reduce the use of closures (because excessive use of closures can result in a lot of undestroyed memory, which can lead to “stack overflow” if not handled properly), and reduce the nesting of closures (reducing the lookup hierarchy of the scope chain).
  • For animation: Those that can be handled with CSS without JS (those that can be handled with transform, which does not use traditional CSS because transform enables hardware acceleration and does not cause reflux, or with positioned elements, which do not affect the position of other elements because they are not in the flow of the document), When a page is in a dormant, unaccessible state, the animation will pause on its own until access is restored. Instead, the timer will process whatever state the page is in, as long as the page is unaccessible
  • Avoid using iframe (because iframe will be embedded in other pages, so the parent page will have to render the child page at the same time, which will slow down the rendering process)
  • Reduced direct manipulation of the DOM (due to reduced DOM reflux and redrawing…) , contemporary projects are basically based on MVVM/MVC data driven view rendering, the DOM operation framework itself completed, performance is much better
  • Low coupling and high cohesion (based on encapsulation: method encapsulation, plug-in, component, framework, class library encapsulation, reduce redundant code in the page, improve code utilization)
  • Use event delegates whenever possible
  • Avoid infinite or nested loops (nested loops multiply the number of loops)
  • Use asynchronous programming as much as possible in projects to simulate the effect of multiple threads and avoid main thread blocking (asynchronous operations are managed based on PROMISE design pattern)
  • Do not use with in JS
  • Avoid CSS expressions
  • Function for damping and throttling
  • Use eval less (the main reason is to prevent code clutter due to improper notation when compressing code)
  • Reduce the use of filters
  • Minimize the number of layers of selectors (selectors are resolved from right to left).
  • Minimize the TABLE layout
  • Manually reclaim stack memory (set to NULL)

108 tips for javascript front-end code optimization 36 tips for Yahoo CSS code optimization

Webpack for performance optimization and security optimization

//=> Stack overflow: dead recurrencefunction func(){ func(); } func(); //=> Solutionfunction func() {setTimeout(func,0); } func(); //=> Interreference: calls between reference types to form nested memory (Height 3)let obj1={
	name:'OBJ1'
};
let obj2={
	name:'OBJ2',
	x:obj1
};
obj1.x=obj2;
Copy the code

What is the AJAX

Async javascript and XML: Asynchronous JAVASCRIPT and XML

  • Asynchronous here refers to: local refresh (corresponding to global refresh)
  • XML: an extensible markup language that stores data in its own custom tags. (In the early days, XML was the predominant data format for our Ajax-based interactions with servers because it clearly showed the corresponding data and structure hierarchy; But later, a new data format, JSON, has become popular, which not only shows the data structure more clearly than XML, but also is more lightweight for the same data storage, which is convenient for parsing and related operations. Therefore, the data interaction between the front and back ends is dominated by JSON format.)

Basic Operations of AJAX

//1. Create an AJAX instanceletxhr=new XMLHttpRequest; //=> < p style = "margin-bottom: 0pt; margin-bottom: 0pt; margin-bottom: 0pt; margin-bottom: 0pt; margin-bottom: 0pt; //METHOD:HTTP request mode //URL: request address (API address) //ASYNC: set synchronous or asynchronous. The default value is TRUE. FALSE synchronization // user-name: USER NAME passed to the server // user-pass: password passed to the server xhr.open('GET'.'./json/xxx.json'.true); Xhr.onreadystatechange = 0 1 2 3 4 xhr.onreadyStatechange = 0 1 2 3 4 xhr.onreadyStatechange = 0function() {if(xhr.readyState===4 && /^(2|3)\d{2}$/.test(xhr.status)){
		letresult = xhr.responseText; Xhr.send (null); //4. => The AJAX task (sending a request to the server and getting the corresponding content from the server) starts after the SEND and ends when xhr. READYSTATE===4Copy the code

HTTP request mode

  • GET Series requests
    • GET
    • DELETE is generally used to tell the server to DELETE something from the server
    • HEAD just wants to get the response header content and tells the server to leave the response body content alone
    • OPTIONS: send a request to the server to see if the server can receive it and return it
  • POST series requests
    • POST
    • “PUT” corresponds to “DELETE”, which usually means that I want the server to store the information I’m passing on to the server (usually applies to files and large data content).

=> Use the corresponding request mode in the real project to make the request more clear (semantic), do not follow these methods is ok, at least the browser syntax is allowed; But these are the norms that developers agree to each other;

The GET series is generally used to GET information from the server, and the POST series is generally used to push information to the server, but both GET and POST can pass information to the server and GET results from the server, it’s just a matter of who has more and who has less

  • GET: Give less, GET more
  • POST: Give more, take less

How does the client pass information to the server?

  • Xhr. open(‘GET’,’/ getData? xxx=xxx&xxx=xxx’)
  • SetRequestHeader xhr.setrequestheader ([key],[value])
  • Set the request body xhr.send(request body information)

How does the server return information to the client?

  • By response header
  • By the response body (most information is returned based on the response body)

Essential differences between GET series and POST series:

The GET series passes information to the server in the following way: question mark passes parameter The POST series passes information to the server in the following way: Set the request body

  1. GET delivers less content to the server than POST, because the URL has a maximum size limit (IE generally limits 2KB, Google chrome generally limits 4 to 8KB, the excessive part is automatically intercepted by the browser).
xhr.open('GET'.'/list? name=xiaokai&year=10&xxx=xxx... ')
xhr.send('....'In theory, there is no limit to the size of the content that can be passed in the request body, but in real projects, we will limit it to ensure the speed of transmissionCopy the code
  1. GET generates caching (which is not under your control) : Because of the requested address (especially the question mark), the browser will sometimes think that you want the same data as the last request. This is the kind of cache that we don’t expect to have, we expect to have a cache that we can control; So in a real project, if we have multiple GET requests for an address, we’re going to remove that cache;
//=> set random number xhr.open('GET'.'/list? name=xiaokai&_='+Math.random()); . xhr.open('GET'.'/list? name=xiaokai&_='+Math.random());
Copy the code
GET and POST requests (for those of you who want to know more about this, check out this brief below)

GET is less secure than POST: GET is passed to the server based on question marks. There is a technique called URL hijacking, which allows others to access or tamper with the information being passed. POST transmits information based on the request body and is not easy to be hijacked.

If you want to see what color underwear GET and POST are wearing 😊 see the link below 👇

This friend writes very well, recommend to everybody

Juejin. Cn/post / 684490…