Optimization of the front end (original)

As long as the front-end optimization in two aspects, one loading speed optimization, the second is the rendering speed optimization. Before performing optimization, to master two basic theoretical knowledge

 

Theoretical knowledge (a): the full load of the rendering process browser

① Enter the url, send a request
② load (ie, download) the entire .html file
③ After loading resolved (ie running) html, and build a DOM tree parsing process
· JavaScript is single-threaded. Browser is a multithreaded: Some thread is responsible for loading resources, some thread is responsible for execution of the script, some thread is responsible for rendering interface.
· From the browser on the principle under (depth traversal) parsing each html tag
process-resolution tag of the process is to build a DOM tree
-analytic encounter link, script, when the img tag, the browser sends a request to the server resources.
script does not affect other resources to load when loading, but because they do not know the contents of the js execution, so the need to wait until after the implementation of JS to load and continue parsing and rendering.
script execution will be blocked html parsing, rendering thread and other threads to download.
resolves to CSSOM (Cascading Style Sheets object model tree containing only one style information) after the link has been loaded css. css load and parse html parsing without blocking, but will block rendering.
img load without blocking the parsing html, but it does not render img after loading, it needs to wait until after the Render Tree and generate Render Tree rendered together. Not downloaded the images would have to wait after downloading rendered.
④ When the css resolved to CSSOM, html parsing of DOM, the two together will generate Render Tree (tree rendering).
⑤Layout (reflow): calculate the shape and position of each node Render Tree. (Waste of performance)
⑥Painting (the repaint): browser rendering styles, colors, backgrounds, borders and size of these elements and so on. (Waste of performance)
⑦Composite (for laminating): browser information will be sent to each of the rendering layers GPU, GPU will be combined in the proper sequence and then the layers displayed on the screen. (GPU composite image, a separate thread, more fluid, but the memory consumption)

 

Theoretical knowledge (2): The browser rendering performance indicators

 Most computer monitors refresh rate is 60Hz, roughly equivalent to 60 times per second redraw, because this frequency is less than the rendering, the page will appear Caton phenomenon, affecting the user experience. Most browsers will be to redraw the operating restrictions, no more than redraw frequency of the display, because even more than the frequency of the user experience will not be improved. Thus, the most preferred smooth animation cycle interval is 1000ms / 60, is approximately equal to 16.6ms. The indicator is the most important indicator of game development.

 

* Front Loading Optimization:
Use outreach CSS and JS: Let the browser cache, reducing the http request. Available webpack automatically increase the hash value of the resource references in the back, on a basis of constant references to browser cache resource is updated. For small cache capacity problem, consider cache localStorage.
· Merge CSS, JS: reducing http requests.
On-demand loading: webpack package is start from the idea of program logic: entry file => Analysis Code => = dependency identify> packaging, such code modules that are not referenced into the bag can not be effectively reduced in volume.
· Press JS module is loaded: for example, if only k echart FIG line module will only load line k.
Compression HTML, CSS, JS: reducing the size of the resource.
· Icon using base64: reduce http requests.
· Icon using Sprite map (svg, font-icon): reduce http requests to reduce the size of the resource.
· Image Compression: picdiet (https://www.picdiet.com/zh-cn), JS is encoded, no size, the size, quantity, default volume can be reduced by 50% on average, substantially no loss of clarity, not compatible problem, you can also adjust the compression ratio.
Avoid pictures and iFrame like empty src: reduce http requests.
· Picture: scroll lazy loading.
· CDN Acceleration: use common resources CDN acceleration to improve speed of response resources, such as jquery, echarts. (Http://www.bootcdn.cn/)
· BigRender first screen rendering optimization: html, js, css and pictures are placed in the textarea lazy loading (https://segmentfault.com/a/1190000006744741).
• Increase Loading progress bar: load cases will be presented to the user.


* HTML, CSS structural optimization:
the less-page labels, the page loading speed faster, and more rapid response.
· Css not load blocked, so the css on the head, to prevent white screen redraw and rearrange content caused by flicker.
· Try to keep class of short, such as: .box: nth-last-child (-n + 1) .title, read: .final-box-title.
· Replace the floating layout with flex layout.
· Remove empty CSS rules: Empty CSS rules increases the size of the CSS file, and the impact of the implementation of CSS tree.
• Do not declare too many font-size: Excessive initiation efficiency CSS font-size tree.
· A value of 0 does not require any units: for compatibility and performance of the browser, is not to take the unit 0:00.
· Rendering display properties affect the page, to be fair use:
①display: after inline should no longer use the width, height, margin, padding and float
②display: should no longer use the float after inline-block
③display: should not be used vertical rear block -align
④display: margin should not be used after * or float table-

* DOM performance optimization: The main is to prevent rearrangement and redraw
· pictures, audio and video width and height before the loaded to 0, so the first static load resources to be prescribed size of the picture.
· Try to avoid Reset Image Size: repeatedly reset the image size will lead to redraw the picture many times
Multi-use requestAnimationFrame (to be learned)
· If you add a parent and child elements at the same time, to be first in memory so the child elements to under the parent element, the parent element was added in one DOM tree.
· If you add more child elements same level at the same time, first joined the same level of sub-elements document fragments, fragments of the document and then added to the overall page. Specifically:
① created document fragment: var frag = document.createDocumentFragment (); document fragments: a plurality of virtual memory levels parent element level sub-element of the temporary storage.
② the same level of sub-elements, first added to the next frag: Use the same common parent element
③ document fragment, add to the overall page
-dom first node display: none; (triggers a rearrangement). Then make a lot of changes, then it is displayed.
· Clone a dom node in memory, after modification; and nodes on-line phase replacement.
· Try to use the ID selector, ID selector is the fastest.
• Each time you choose to be calculated Dom, he cache to avoid genlock layout (force reflow).
• For modify elements of multiple styles, you can use cssText attribute to avoid forced synchronization layout. For example the following, the trigger 3 reflows:
var = document.getElementById EL ( 'myDiv');
el.style.borderLeft = '1px';
el.style.borderRight = '2px';
el.style.padding = '5px';
into this, only rearrangements 1:
var = document.getElementById EL ( 'myDiv');
el.style.cssText = 'border-left: 1px; border-right: 2px; padding: 5px; ';
defines a class is changed to a plurality of styles, and then by adding className class required.
· More use of animation transform and opacity, they would lead to the synthesis, layout and does not cause redraw.
• If an element needs to redraw the layer, then the entire layer needs to be redrawn. Created with translateZ (0) manually render layer, reducing the required number of pixels rendered, the GPU may also be accelerated. But do not abuse the property, which would significantly increase memory consumption. (For more details: https: //developers.google.
CN / Web / Fundamentals / Performance / Rendering / Simplify-Paint-Complexity-the reduce-and-Paint-Areas) · Do not use table layouts, a small change will result in re-layout of the entire table.
· Animation instead of using css js animation: css animation has an important feature that is fully working on the GPU. Because you declare an animation of how to start and how to end, the browser will be ready all the instructions needed before the animation begins; and sends them to the GPU. If using js animation, the browser must calculate the status of each frame; in order to ensure smooth animation, we must calculate a new state in the browser main thread; send them to the GPU at least 60 times per second. In addition to calculating and transmitting data slower than css animation, the main thread of the load will also affect the animation; too many computing tasks when the main thread will cause the animation delay Caton. So as much as possible using css-based animation, not just quicker; it will not be a lot of computing js blocked.
• Reduce the size of the composite layers: You can size the image by 5% --10% and then use the scale to make them larger; users will not see any difference, but you can reduce the amount of storage space.
· Virtual DOM technology: for example Vue, React and other frameworks on the use of virtual DOM.

* script Optimization:
· We know that the script will be loaded and run blocking page, so it should be the <script> tag into the final.
· JS: throttle function (throttle): Perform only once every XX seconds; (https://segmentfault.com/a/1190000006722279)
· JS: Debounce function (anti-shake): When the continuous trigger function is called, in the final It began after the first call once triggered XX seconds. (https://segmentfault.com/a/1190000006732819)
· For multi-conditional, Dictionary faster than if-else.
Avoid rapid succession layout:
Before improvement: resizeWidth function () {
// make browser into 'read write' cycle
for (var I = 0; I <paragraphs.length; I ++) {
the Paragraphs [I]. + = box.offsetWidth style.width 'PX';
}
}
after improvement: var width = box.offsetWidth;
function resizeWidth () {
for (var I = 0; I <paragraphs.length; I ++) {
the Paragraphs [I]. width = + style.width 'PX';
}
}
· Depth deeper prototype chain, the search speed will be slower. Remember, the search process instance members or local variable amount of direct burden heavier, so traverse the prototype chain to increase the cost of just amplify this effect than access.
· Search function scope chain will consume performance, global variables are always at the end of the scope chain, it takes the longest. The best use of local variables as possible. A good rule of thumb is: the value of a local variable stored by the variable outside the local range.
· Members nested deeper, slower access speeds. location.href always faster than window.location.href, and the latter than window.location.href.toString () faster. If the instance of these attributes is not an object, then you have to search members analytical prototype chain at each point, which will take longer.
· Simplified calculation, such as: for (var = I 2; I <= the Math.sqrt (n-); I ++) {IF (n-I% == 0) {}} return to false
-mentioned earlier should be rendered in each frame completed within 16ms, but the animation process, because they have occupied a lot of time, so time-consuming to run JavaScript code should be controlled at 3-4 milliseconds. If there is extremely time consuming and does not operate purely computational work DOM elements, can be considered Web Workers put in execution.


* Server settings to optimize:
* cache all cacheable resources: http caching.
• Use long-Cache, 304 redirect to avoid: the premise of the mobile terminal network instability, one more request, multi-part load time.
Use DNS cache: browser will reduce the time spent in DNS Resolution.
· Enable GZip: GZip is part of the http protocol, used to compress the size of the page.
* Image compression: the default front-end to generate a thumbnail biography.
Reduce Cookie: Cookie will affect the loading speed, so static resource domain does not use Cookie.
· DNS: to reduce the number of DNS - reduce cross-site reference external resources.
• Create a connection: reduce the number of connections created - using the Keep-Alive connection to avoid duplication.
· Wait for a response: to improve server speed - to improve operations and data query speed.

Guess you like

Origin www.cnblogs.com/jacksplwxy/p/10948914.html