Front-end optimization

Links:Front-end optimization

Front-end optimization

The browser sends an HTTP request, and the server returns an HTTP response after receiving the full request, ending the process after the browser receives it. The browser and the server have only one chance to interact. The browser initiates actively, while the server passively returns the result according to the received request content. A complete request requires the process of DNS addressing, establishing a connection with the server, sending data, waiting for the server to respond, and receiving data.

Ways to Optimize Front End

  1. Page levelOptimization of, for example, the number of HTTP requests, non-blocking loading of scripts, location optimization of inline scripts, etc.
  2. Code levelFor example, DOM operation optimization, CSS selector optimization, picture optimization and HTML structure optimization in JavaScript.

Page level optimization

1. Reduce the number of HTTP requests

The Main Way to Reduce the Number of HTTP Requests

1. Simplify the page from the design and implementation level

Keep pages concise and reduce the use of resourcesIs the most direct. Use CSS instead of pictures as little as possible.

2. Set HTTP cache reasonably

Proper cache settings can greatly reduce HTTP requests. The request server of the cached resource is 304 response, onlyHeaderNobody, no bandwidth savings. For codes that can be used on multiple pages, try to split them into the same file. If the page is embedded, the volume of the page is increased, and the browser cache cannot be used.

3. Resource Consolidation and Compression

If possible, merge external scripts and styles as much as possible, and combine multiple into one. In addition, CSS, JavaScript and image can all be compressed with corresponding tools.

4、CSS Sprites

There is a good way to reduce the number of requests by merging CSS images.

5、lazy load image

This strategy does not necessarily reduce the number of HTTP requests, but it can reduce the number of HTTP requests under certain conditions or when the page is just loaded. For pictures, only above the fold can be loaded when the page is just loaded, and subsequent pictures will be loaded when the user continues scrolling back. The previous method was to cache the image address after above the fold in the loading processtextareaIn the label, only when the user scrolls down the screenInertiaLoad. Baidu pictures and petal nets also use this popular waterfall stream to load pictures.

2. Set the external script to the bottom

External chain scripts block other resources when loaded, for example, the pictures, styles and other scripts behind the script are blocked until the script is loaded, and will not start loading until the script is loaded. If the script is placed at a higher position, it will affect the loading speed of the whole page and thus affect the user experience. The simplest and most reliable method is to move the script back as far as possible to reduce the impact on concurrent downloads. If timeliness permits, it can be considered inDOMLoadedLoad when an event is triggered, or use thesetTimeoutTo flexibly control the timing of loading.

3. Asynchronous executioninlineScript

inlineScripts have a much greater impact on performance than external scripts. First, like external scripts,inlineScripts also block concurrent requests when executing. In addition, because browsers are single-threaded when dealing with pages, wheninlineWhen the script is executed before the page is rendered, the rendering of the page will be delayed. In short,inlineThe page is blank when the script is executed.

In view of the above two points, it is suggested thatThe execution time is longinlineAsynchronous script execution. There are many ways to execute asynchronously, such as usingscriptelementarydeferProperties, usagesetTimeoutIn addition, HTML5 introducesweb workersThis kind of problem can be solved precisely through the mechanism of the.

4.lazy load JavaScript

At present, there are about two ways to do this. One is to customize a special page for pages with extremely large traffic.miniVersion of the frame, the other islazy load, initially only the core module is loaded, and other modules can be loaded only when needed, similar tojavaTheswingTo import the required component library files.

5. Place CSS inheadIn

6. Reduce unnecessary HTTP jumps

For HTTP links accessed in the form of directories, many people will ignore whether the link is finally brought/If the server treats this differently, then 301 hops are probably hidden and redundant requests are added.

Code level optimization

1.JavaScript

1、DOM

DOM operations should be the most performance-intensive type of operations in scripts, such as adding, deleting, checking, modifying DOM elements, or operating on DOM collections. Note if the script contains a large number of DOM operationshtml collection.

In the scriptdocument.imagesdocument.formsgetElementsByTagName()All returned areHTMLCollectionA collection of types is usually used as an array because it haslengthProperty, you can also use indexes to access each element. However, the access performance is much worse than that of arrays, because this set is not a static result, it represents only a specific query, and this query will be re-executed every time the set is accessed to update the query results. So – calledAccess setThe that includes the read collectionlengthProperty to access elements in the collection.

Therefore, when you need to traverseHTML collectionWhen, try to put itAccess after converting to arrayTo improve performance. Even if it is not converted to an array, please access it as little as possible, for example, you can convert thelengthProperties and members are saved to local variables before using local variables.

2. Be carefulwith

with(obj){p=1};The behavior of the code block is actually to modify the execution environment in the code block, which willobjOn the front end of its role, inwithAccess to non-local variables in a code block starts withobjOn the start of the search, if you don’t press the scope chain to look up in turn, thereforeUsewithThis is equivalent to increasing the length of scope chain.. However, it takes time to find scope chain every time, and too long scope chain will lead to a decline in search performance.

Therefore, unless you canDefinitelywithOnly put in the codeobjProperties in, otherwise be carefulwithInstead, you can use local variables to cache the attributes that need to be accessed.

3. Avoid usingevalAndFunction

Every timeevalOrFunctionWhen a constructor acts on the source code represented by a string, the script engine needs to convert the source code into executable code. This is a resource-consuming operation-usually more than 100 times slower than simple function calls.

evalThe efficiency of the function is particularly low, because it cannot be known in advance toevalThe contents of the string of the,evalParsing the code to be processed in its context means that the compiler cannot optimize the context, so only browsers can parse the code at runtime, which has a great impact on performance.

FunctionConstructor ratioevalSlightly better, because using this code will not affect the surrounding code, but its speed is still very slow.

In addition, the use ofevalAndFunctionNot conducive to JavaScript compression tools to perform compression.

4. Reduce scope chain Search

Scope chain looks for problems, which requires special attention in the cycle. If you need to access variables that are not under this scope in a loopPlease cache the variable with a local variable before traversing and repeat that variable after traversing, which is especially important for global variables, because global variables are at the top of the scope chain, and the number of lookups during access is the largest.

In addition, to reduce scope chain lookups, you should also reduce the use of closures. Closure variables may be stored in memory, which consumes a lot of memory. The solution is to delete unused local variables before exiting the function.

5. Data Access

Data access in JavaScript includes direct variables (strings, regular expressions), variables, object attributes, and arrays. Among them, direct variables and local variables are the fastest to access, and access to object attributes and arrays requires more overhead. It is recommended to put data into local variables when:

  1. For anyObject propertiesMore than 1 visit to
  2. For anyArray memberMore than 1 visit to

In addition, should also be as far as possibleReduce depth search for objects and arrays.

6. String splicing

Use in JavaScript+Number to splice string efficiency is relatively low, because every run will open up new memory and generate new string variables, and then the splicing results assigned to new variables. Before using jQuery+Ajax interactive pages, most of the time it was the data and front end transferred from the background.HTMLThe structure is spliced into strings and then rendered in the HTML container of the page.

Compared with this, it is more efficient toUsing arraysjoinMethodThe string to be spliced is placed in the array and finally calledjoinMethods The results were obtained. However, due to the overhead of using arrays, this method can be considered when there are many strings to be spliced.

2. CSS selector

In most people’s minds, browsers interpret CSS selectors from left to right.

If it is analyzed from right to left, the efficiency will be very high, because the first ID selection basically limits the search scope, but in fact the browser analyzes the selector from right to left.#tag A {color: "#ccc"; }, the browser must traverse to find eachAThe efficiency of the ancestor node of the tag is not as high as previously thought. According to this behavior characteristic of the browser, many matters need to be paid attention to when writing selectors.