Reduce the number and size of HTTP requests
Code optimization
- Is conducive to SEO
- Facilitate extended maintenance
- Helps reduce performance costs
- 108 suggestions for javascript code optimization [36 Suggestions for CSS optimization]…
Optimization of DNS and HTTP communication mode
1. Minimize the use of closures in JS (reasons: Closures create unreleased stack memory) A: When loop to element event binding, try to store the information needed later (such as index) on the element’s custom attribute instead of creating closure store B: Can form A closure on the outermost layer, store some public information needed later. Instead of creating closures for every method (e.g., singleton mode) C: Manually free up unused memory as much as possible…
2. Try to merge CSS and JS files (merge the CSS that needs to be introduced into one, JS is also merged into one), the principle is to reduce the number of HTTP requests, compress the merged code as far as possible, reduce the size of HTTP request resources A: Webpack, an automatic construction tool, B: In mobile development (or the pursuit of high performance PC development [such as Baidu home page]), if CSS or JS is not a lot of needs, we can choose to embed CSS and JS programming (that is, the code is written directly in HTML)
3. Try to use font ICONS or SVG ICONS instead of traditional PNG images (because font ICONS are vector images (written based on code), which will not be deformed when enlarged, and render faster, smaller than bitmaps)
4. Reduce DOM operations (mainly to reduce DOM redrawing and backflow (rearrangement)) A: Separate read and write about rearrangement B: use document fragments or string splicing for data binding (dynamic creation of DOM)
5. Avoid “nested loops” (which add a lot of extra loops) and “dead loops” (which cause the browser to freeze) in JS
6. The purpose of “lazy loading” (lazy loading) of images is to reduce the number of HTTP requests in the process of “first loading” of the page and make the page open faster steps: When the page starts loading, all real images do not send HTTP requests for loading, but are given a placeholder for the background image. When the page is loaded and the image is in the visible area, we load the image again
7. Use the browser and server side of the cache technology (304 cache), some not often updated static resource files do cache processing (such as: JS, CSS, static images can do cache) principle is to reduce the HTTP request size, so that the acquisition speed is faster
8. Use event delegate (event proxy) as far as possible to handle the operation of event binding and reduce frequent DOM operations, including event binding for each DOM element
9. Minimize the use of CSS expressions
#myDiv {
position: absolute;
width: 100px;
height: 100px;
left: expression(document.body.offsetWidth - 110 + "px");
top: expression(document.body.offsetHeight - 110 + "px");
background: red;
}
Copy the code
CSS selector parsing rules are parsed from right to left
.container. Link a{find all the a's in the.link style class, filter again in the.container style class... We find all the A's first, which is A performance drain. We use CSS selectors to minimize the use of label selectors.Copy the code
11.CSS Sprite graph technology (CSS Sprite/CSS image Sprite) put all relatively small resource images into a large picture, later we just need to load down the large picture, with the way of background positioning to show the corresponding small picture
.bg{
background:url('xxx.png');
}
.box1{
background-position:xx xx;
}
.box2{
background-position:xx xx;
}
<div class='bg box1'></div>
Copy the code
13. Reduce the use of cookies (the most important is to reduce the size of local COOKIE storage), because when the client operates cookies, these information is always passed between the client and server side
14. Data acquisition in the page adopts asynchronous programming and delayed batch loading to use asynchronous data acquisition, in order to reduce the BLOCKING of THE HTTP channel, will not delay the rendering of the following information because there is no data request back, improve the speed of the page opening (we can deal with: Delay batch loading is similar to image lazy loading, in order to reduce the number of HTTP requests during the first page loading
15. The audio and video labels appear on the page, we don’t want to load these resources when the page is loading (otherwise the page will load slowly) (solution: just set preload=’ None ‘), wait for the page to load, we load audio and video resources when the audio and video is playing
16. In the information interaction between the client and the server, we try our best to transmit a number of data based on JSON format (JSON format is convenient for data processing and has small resources) ==> Compared with THE TRANSMISSION in XML format
17. Achieve JS encapsulation as far as possible (low coupling and high cohesion), reduce redundant code in the page (reduce the size of HTTP request resources)
20. After setting positioning in CSS, it is better to use z-index to change the hierarchy of boxes so that all boxes are not on the same plane, so that the performance of subsequent processing can be slightly improved
21. During the data interaction of ajax-based GET requests, we can make it generate a cache (this cache is not the 304 cache) according to the requirements, so that the next data obtained from the same address is the last cached data (but it is rarely used, and the project usually deliberately clear this cache more often).
22. Minimize the use of the Filter attribute (this attribute is more performance intensive)
23. In the CSS import, try to reduce the use of @import import, because @import is a synchronous operation, only the corresponding CSS import, will be loaded down, and link is asynchronous operation
24. Configure ETag(somewhat similar to 304 cache)
25. The use of the window. RequestAnimationFrame frame animation in (JS) instead of the traditional animation timer
26. Reduce the use of recursion to avoid dead recursion and stack memory nesting caused by recursion (tail recursion is recommended)
27. Avoid using iframe (not only is it difficult to control style, but also equivalent to loading other pages in page A, which consumes A lot of energy)
28. Make use of the localstorage localstorage or the manifest offline cache provided in H5 to store some information locally, and obtain it directly from the local when loading the page next time to reduce the number of HTTP requests
29. When retrieving JS based on SCRIPT, you can already use defer or Async to load asynchronously
Heavyweight optimization: CDN acceleration (cash burning machine)
=== Extra technique ===
1. We usually place the CSS on top of the BODY and the JS on top of the BODY. (Reason: let it load the CSS first.
2. CSS does not use JS, native JS does not use plug-ins, FLASH does not use (except for audio and video playback of the lower version of the browser) =>CSS processing animation and other functions better than JS performance, and CSS transform also turned on hardware acceleration
3. Try to reduce the use of EVAL in JS, because when JS is merged and compressed, the code execution priority may be wrong due to imperfect symbols, and EVAL processing consumes a bit more performance
4. Use keep-alive to establish a long connection between the client and server
5. Try to use design patterns to manage our code (singleton, construct, Promise, publish and subscribe) for later upgrades and maintenance
6. Enable gzip compression on the server side (this compression can effectively reduce the size of the requested resource file). In fact, resources such as images on the client side can also be compressed (but for the 24-bit bitmap, the compression may become blurred).
7. Do not have invalid links in the page (good for SEO optimization), there are other techniques: improve keyword exposure, img need to add Alt, set meta tags, tag semantics…
8. Avoid with statements (performance hogging)
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
AJAX
Async javascript and XML in AJAX is not synchronous asynchronous programming as we understand it, but a general term for “local refresh”. However, we will use asynchronous data fetching as much as possible in future AJAX requests (since asynchronous data fetching does not block the execution of the following code).
XML is a file format (we can think of HTML as a kind of XML) : extensible markup language, which is used to store some data and content with its own extended semantic tags. The advantage of such storage is that the structure of the data is clearly displayed
A long time ago, when AJAX was just getting started, the client would fetch data from the server, and the server would return XML in order to clearly express the data structure. Now, the data we get is usually JSON, and JSON can clearly express the data structure compared to XML. And data access inside the easier to operate than XML (but now some projects, not just returned from the server to the client data is the data, but data and needs to show the structure of the stitching good results (similar to our own do string concatenation), in other words, is the server and the data structure together is returned to us, The data returned is usually a string in XML format.
2. AJAX operation
//=> Create AJAX instance: IE6 is incompatible and uses new ActiveXObject to implement itletxhr = new XMLHttpRequest(); //=> Open request: Send the request before some of the configuration items / / 1. The HTTP request METHOD way / / GET/DELETE/HEAD/OPTIONS/TRACE/CONNECT / / POST/PUT / / 2. The URL to send the request to the server API (Application ASYNC Sets the asynchron of AJAX requests. The default is asynchron (write TRUE is asynchron), FALSE is asynchron (write TRUE is asynchron). Xhr.open ([HTTP METHOD],[URL],[ASYNC],[user-name],[user-pass]); //4. User-name/user-pass: indicates the USER NAME and password. Xhr.onreadystatechange =()=>{//=>3.if(xhr.readyState===4 && xhr.status===200){ xhr.responseText; }}; Xhr.send ([request body]); xhr.send([request body]); xhr.send([request body])Copy the code
3. A little learning about HTTP request methods
GET: Obtains data from the server. POST: pushes data to the server. DELETE: deletes some content from the server. HEAD: only want to get the response header returned by the server. Do not respond to the content in the body. It is usually used to send a probing request to the server. If the server returns a message indicating that the client has established a connection with the server, we can proceed with other requests. (TRACE does this, but axios, the AJAX library, does this when making cross-domain requests. If the server can be connected, other requests will be sent.)
4.GET VS POST
[Different ways of sending information to the server] GET sends information to the server based on the question mark parameter of the URL address, and POST sends information to the server based on the request body
[GET]
xhr.open('GET'.'/temp/list? xxx=xxx&xxx=xxx')
[POST]
xhr.send('xxx=xxx&xxx=xxx')
Copy the code
GET is usually used to fetch (less to the server), while POST is used to send a lot to the server. If POST is based on the question mark method, there are some problems: THE URL will be long concatenation, and the browser has a maximum length of URL (Google 8KB, Firefox 7KB, IE2KB…). So the GET request can be passed based on the URL, while the POST is passed using the request body (there is no limit to the request body in theory. In real projects, we will set the size limit ourselves to prevent the request from being delayed due to uploading too much information).
[GET is not secure, POST is relatively secure]
Because GET transmits information to the server based on “question mark transmission”, it is easy to be URL hijacked by hackers. POST is transmitted based on the request subject, which is relatively difficult to be hijacked. Therefore, we should use POST requests for security interactions such as login and registration.
[GET creates an uncontrollable cache,POST does not]
We can’t control it based on JS. In real projects, we would kill this cache. GET requests are cached because: If you send multiple requests to the same address (and pass the same parameter information), the browser will retrieve the data from the cache, causing the server to fail to retrieve the latest data (POST does not).
Solution:
xhr.open('GET',`/temp/list? lx=1000&_=${Math.random()}`); //=> Ensure that the address of each request is not exactly the same: append a random number to the end of each request (use _ as attribute name to avoid conflict with other attribute names)Copy the code
5. AJAX status (READY – STATE)
- 0 =>UNSENT The XHR is created and has not been sent
- 1 =>OPENED has been OPENED
- 2 =>HEADERS_RECEIVED AJAX request has been sent (AJAX task started), and the response header information has been received by the client (the response header contains: server time, returned HTTP status code…).
- 3 =>LOADING The response body is returning
- 4 =>DONE The response body is received by the client
6.HTTP Network STATUS Code
The result and cause of the current interaction can be clearly reflected according to the status code
-
200 OK success (only to prove that the server successfully returned information, but not necessarily the information your business needs)
-
301 Moved Permanently migrate Permanently (permanent redirection) => Change the domain name. Access the original domain name and redirect it to a new domain name
-
302 Move temporarily (Temporarily redirect =>307) => The website operates using HTTPS. If you access the website through HTTP, the website is redirected to HTTPS based on 307. When a server to maximize concurrency, the follow-up visit user temporary transfer to other server unit processing = > occasionally in real project will put all of the images on a single server “image processing server”, so reduce the pressure of the primary server, when the user access to the main server images, The master server moves it to the image server for processing
-
304 Not Modified Cache => For resource files that are Not frequently updated, such as CSS/JS/HTML/IMG, the server will set the 304 cache with the client. After loading these resources for the first time, the server will cache them to the client and obtain them from the cache next time. If the resource is updated, the server will force the client to pull it from the server by last changing the time. With CTRL+F5 forcing the page refresh, the cache 304 does is useless.
-
400 Bad Request The Request parameters are incorrect
-
401 Unauthorized No access
-
404 Not Found resource Not Found
-
413 Request Entity Too Large The content resources interacting with the server exceed the upper limit of the server
-
500 Internal Server Error Indicates an unknown Server Error
-
503 Service Unavailable The server is overloaded
7. Attributes and methods about XHR
Xhr. response Indicates the response body
xhr.responseText
The content of the response body is a string (either in JSON or XML format) xhr.responsexml The content of the response body is an XML document
Xhr. status Description of the returned HTTP status code xhr.statusText
Xhr. timeout Sets the timeout period for the request. Xhr. withCredentials Whether cross-domains are allowed (FALSE)
XHR. Abort () forced interrupt the AJAX request XHR. The getAllResponseHeaders () to get all the response headers XHR. GetResponseHeader ([key]) to obtain the key corresponding to the response headers, such as: Xhr.getresponseheader (‘date’) is the server time in getting the response
Xhr.open () opens the URL request xhr.overridemimeType () overrides the MIME type xhr.send() sends the AJAX request xhr.setrequestheader () sets the request header