1. How to use the CSS to improve page performance?
One, foreword
Every web page is inseparable from CSS, but many people think that CSS is mainly used to complete the layout of the page, like some details or optimization, do not need to consider, in fact, this idea is not correct
As an important part of page rendering and content presentation, CSS affects the user’s first experience of the whole site
Therefore, CSS performance optimization also needs to be implemented throughout the entire product development process
Second, the way of implementation
There are many ways to achieve, mainly as follows:
- Inline first screen key CSS
- Loading the CSS asynchronously
- Resources compression
- Use your selectors wisely
- Reduce the use of expensive attributes
- Do not use @import
Inline first screen key CSS
When a page is opened, the amount of time the first content of the page appears on the screen affects the user’s experience, and inline CSS key code enables the browser to render the HTML as soon as it is downloaded
If an external reference to the CSS code is encountered during the parsing of the HTML structure, the CSS code will be downloaded and rendered
Therefore, using CSS inline makes rendering time advance
Note: However, large CSS code is not suitable for inlining (initial congestion window, no caching), while the rest of the code is externally referenced
Loading the CSS asynchronously
Until the CSS file is requested, downloaded, and parsed, the CSS blocks rendering and the browser will not render any processed content
When the inline code is loaded earlier, the external CSS reference does not necessarily block the browser rendering. In this case, the asynchronous loading scheme can be adopted, mainly as follows:
- Use javascript to insert the link tag at the end of the head tag
Const myCSS = document.createElement("link"); myCSS.rel = "stylesheet"; myCSS.href = "mystyles.css"; / / insert to the header of the final location document. The head. The insertBefore (myCSS, document.head.childNodes[ document.head.childNodes.length - 1 ].nextSibling );Copy the code
- If you set the link TAB media attribute to noexis, the browser will assume that the current style sheet does not apply to the current type and will download it without blocking the page rendering. When the load is complete, the
media
The value of the setscreen
orall
To get the browser to start parsing the CSS
<link rel="stylesheet" href="mystyles.css" media="noexist" onload="this.media='all'">
Copy the code
- If you set the link TAB media attribute to noexis, the browser will assume that the current style sheet does not apply to the current type and will download it without blocking the page rendering. When the load is complete, the
media
The value of the setscreen
orall
To get the browser to start parsing the CSS
<link rel="alternate stylesheet" href="mystyles.css" onload="this.rel='stylesheet'">
Copy the code
Resources compression
Modularized tools such as Webpack, gulp/grunt, and Rollup are used to compress CSS code to make the file smaller and greatly reduce the browser load time
Use your selectors wisely
The CSS matches from right to left. For example, # markdown. content h3 matches as follows:
- Find the H3 tag element first
- Then remove the elements whose ancestors are not.content
- Finally, remove elements whose ancestors are not # markDown
If there are more layers nested and more elements in the page, the time cost of matching is naturally higher
So when writing a selector, we can follow the following rules:
- Do not nest too many complex selectors, preferably no more than three layers
- Using the ID selector eliminates the need for nesting
- Wildcards and attribute selectors are the least efficient and should be avoided
Reduce the use of expensive attributes
Expensive properties such as box-shadow/border-radius/filter/ transparency /:nth-child will degrade the rendering performance of the browser when the page is redrawn
Do not use @import
CSS style files can be imported in two ways, one is the link element and the other is @import
@import affects parallel downloads in the browser, adding extra delay to page loading and adding extra round trips
And multiple @imports may cause the download order to get out of order
For example, a CSS file index.css contains the following: @import URL (“reset.css”)
The browser must download, parse, and execute index.css before downloading, parsing, and executing the second file reset.css
other
- Reduce rearrangement operations, and reduce unnecessary redraws
- Know which properties can be inherited and avoid writing them repeatedly
- CssSprite, synthesizes all icon images, and displays the icon images we want by using the background image of width and height plus backgroud-position, reducing HTTP requests
- Convert small icon images to Base64 encoding
- CSS3 animations or transitions should be animated using transform and opacity instead of left and top
Third, summary
CSS performance can be achieved in terms of nesting selectors, property features, and reduced HTTP, as well as the order in which CSS code is loaded
2. How to solve the slow loading speed of the first screen of SPA (single-page application)?
What is the first screen loading
First Contentful Paint is the time it takes the browser to render the First screen of content in response to the user’s input of a web address. This time the entire page does not have to be rendered, but the content needed for the current window is displayed
The first screen load is arguably the most important part of the user experience
About calculating the first screen time
Using data provided by Performance. Timing:
Calculate the first screen time using DOMContentLoad or Performance
/ / plan: document. AddEventListener (' DOMContentLoaded '(event) = > {the console. The log (' first contentful painting'); }); // Plan 2: performance.getEntriesByName("first-contentful-paint")[0].startTime // Performance. GetEntriesByName (" first - contentful - paint ") [0] / / returns a PerformancePaintTiming instance, structure is as follows: {name: EntryType: "paint", startTime: 507.80000002123415, duration: 0,};Copy the code
Second, the reason for the slow loading
During page rendering, the following factors may cause slow loading:
- Network delay problem
- Whether the resource file size is too large
- Did the resource send repeated requests to load
- The render content was blocked while loading the script
Third, solutions
Several common SPA first screen optimization methods
- Reduce the entry file product
- Local cache of static resources
- The UI framework loads on demand
- Compression of image resources
- Component repackaging
- The GZip compression function is enabled
- Using SSR
Reduce the entry file size
The common method is lazy route loading. Components corresponding to different routes are divided into different code blocks. When a route is requested, the route is packaged separately, which makes the entry file smaller and greatly increases the loading speed
When routes are configured on the VUe-router, routes are dynamically loaded
routes:[
path: 'Blogs',
name: 'ShowBlogs',
component: () => import('./components/ShowBlogs.vue')
]
Copy the code
The route is loaded as a function so that each route file can be packaged separately, and the routing component is loaded only when a given route is resolved
Local cache of static resources
Backend return resource problem:
- using
HTTP
Cache, SettingsCache-Control
.Last-Modified
.Etag
Such as response headers - using
Service Worker
Offline caching
The front-end uses localStorage properly
The UI framework loads on demand
In everyday use of UI frameworks such as Element-UI, or ANTD, we often drink directly from the entire UI library
import ElementUI from 'element-ui'
Vue.use(ElementUI)
Copy the code
import { Button, Input, Pagination, Table, TableColumn, MessageBox } from 'element-ui';
Vue.use(Button)
Vue.use(Input)
Vue.use(Pagination)
Copy the code
But the only components I actually use are buttons, pages, tables, inputs and warnings so we need to refer to them as needed
import { Button, Input, Pagination, Table, TableColumn, MessageBox } from 'element-ui';
Vue.use(Button)
Vue.use(Input)
Vue.use(Pagination)
Copy the code
Component repackaging
Assuming that the a.js file is a common library, there are now multiple routes using the A.js file, which results in repeated downloads
Solution: In the Config file of WebPack, modify the configuration of CommonsChunkPlugin
minChunks: 3
Copy the code
A minChunks of 3 means that packages that have been used three or more times will be pulled out and put into a common dependency file, avoiding reloading components
Compression of image resources
Image resources are not part of the coding process, but they have the biggest impact on page performance
For all the image resources, we can do appropriate compression
For the ICONS used on the page, you can use online font ICONS or Sprite images to combine many small ICONS into a single image to relieve the pressure of HTTP requests.
The GZip compression function is enabled
After unpacking the package, let’s do some compression with gzip to install the Compression-webpack-plugin
cnmp i compression-webpack-plugin -D
Copy the code
Introduce and modify the WebPack configuration in vue.congig.js
const CompressionPlugin = require('compression-webpack-plugin') configureWebpack: (config) => {if (process.env.node_env === 'production') {// Modify the configuration for the production environment... Config. Mode = 'production' return {plugins: [new CompressionPlugin ({test: / \. Js $| \. HTML $| \. CSS /, / / matching filename threshold: DeleteOriginalAssets: false // Whether to delete the original file})]}}Copy the code
We also have to configure it on the server so that if the browser that’s sending the request supports GZIP, you send it a GZIP file and my server is built using the Express framework and you just need to install compression to use it
Const compression = require('compression') app.use(compression()) // called before other middleware uses itCopy the code
Using SSR
SSR (Server Side), or Server side rendering, where components or pages generate HTML strings from the Server and send them to the browser
Building a server-side rendering from scratch can be complicated, and the Vue application recommends using NuxT.js for server-side rendering
Summary:
There are many ways to reduce the first screen rendering time, which can be divided into two main parts: resource loading optimization and page rendering optimization
Below is a more comprehensive first screen optimization
3. What is the difference between async and defer in the script tag?
The following three types of scripts are encountered in HTML:
<script src='xxx'></script>
<script src='xxx' async></script>
<script src='xxx' defer></script>
Copy the code
In this case, the script tag provides two ways to solve the problem by adding the properties async and defer, both of which enable the script tag to load without blocking the DOM rendering.
For example, people are used to referencing various third-party scripts in the page, but if the third-party service has some small problems, such as delay, will make the page blank.
The script tag is used to load and execute the script. When a script is used directly, HTML will load and execute the script in sequence. During the loading and execution of the script, subsequent DOM rendering will be blocked.
Defer: The Boolean property is set to instruct the browser to execute the script after the document has been parsed. Async: Set this Boolean property to instruct the browser to execute the script asynchronously if possible.Copy the code
defer
If the script tag sets the defer property, the browser will download the file asynchronously without affecting subsequent DOM rendering.
If more than one script tag exists with the defer property set, all scripts are executed in order, as the defer script is executed after the document has been rendered and before the DOMContentLoaded event is called.
async
The async property causes scripts to be loaded asynchronously and executed when allowed. Async execution does not follow the order in which script tags are loaded on the page.
4. What performance optimizations can be made in React?
- Use shouldComponentUpdate to avoid unnecessary renderings, but if you make a deep comparison between props and state, it’s expensive, so you need to make some trade-offs depending on the business; In the case of child components, in order to avoid repeated rendering of the child components, the parent component can be used to determine whether the child needs a PureRender.
- Set props to an array or object: Each call to the React component creates a new component. Even if the array or object value passed in does not change, their reference address will also change. For example, if you write as follows, style will be a new object every time you render
< / button style={{color: 'red'}} /> 'red'} < button style = {style} / > / / do not recommend < button style = {this. Props. Style | | {}} / > / / recommend const defaultStyle = {} "button style={this.props.style || defaultStyle } />Copy the code
-
Move the binding of the function inside the constructor: you can avoid binding the event every time.
-
When we use reference types that are immutable, we recommend shallowCopy and deepCopy to avoid affecting the original data, but this will waste CPU and memory. Therefore, immutable is recommended. The advantages are as follows
- Reduces the complexity of “variable”
- Memory saving, immutable uses structure sharing to overuse memory as much as possible. Objects that are not referenced are garbage collected
- Better at undo/redo, copy/paste, time travel
- No concurrency issues (because the data itself is immutable)
- Embrace functional programming
-
Give the child component a unique key, because in the DIff algorithm, the key is used as a unique identifier to optimize the rendering
5. Talk about common front-end performance optimization methods
-
The content in
- Reduced HTTP requests: merge files, CSS sprites, inline Images
- Reduced DNS query: The browser cannot download any files from this host until the DNS query is complete. Methods: DNS caching, distributing resources to the right number of host names, balancing parallel downloads and DNS queries
- Avoid redirection: redundant intermediate access
- Make Ajax cacheable
- Non-essential components are loaded lazily
- Future required components are preloaded
- Reduce the number of DOM elements
- Place resources in different domains: Browsers can only download a limited number of resources from one domain at a time. Adding domains can increase concurrent downloads
- Example Reduce the number of iframe
- Don’t 404
-
The Server side
- Use the CDN
- Add the Expires or cache-control response header
- Use Gzip compression for components
- Configure the ETag
- Flush Buffer Early
- Ajax uses GET to make requests
- Avoid empty SRC img tags
-
Cookie aspects
- Reduce cookie size
- The domain name of the imported resource does not contain cookies
-
CSS aspects
- Place the style sheet at the top of the page
- Do not use CSS expressions
- The Filter of Internet Explorer is not used
-
In Javascript
- Place the script at the bottom of the page
- Import javascript and CSS from the outside
- Compress javascript and CSS
- Delete unnecessary scripts
- Reduce DOM access
- Design event listeners properly
-
pictures
- Optimize the picture: according to the actual color needs to choose color depth, compression
- Optimized CSS sprites
- Do not stretch images in HTML
- Keep favicon.ico small and cacheable
6. How to optimize front end performance with WebPack
Optimizing front end performance with WebPack means optimizing the output of WebPack so that the packaged end result runs quickly and efficiently in the browser.
- Code compression: Ways to remove redundant code, comments, simplify how code is written, and so on. Can take advantage of WebPack
UglifyJsPlugin
andParallelUglifyPlugin
To compress the JS file, usingcssnano
– loader (CSS? Minimize) to compress CSS - CDN acceleration: During the build process, change the referenced static resource path to the corresponding path on the CDN. You can use WebPack for
output
Parameter and each loaderpublicPath
Parameter to modify the resource path - Tree Shaking: Removing pieces of code that will never be seen. You can do this by appending parameters when you start WebPack
--optimize-minimize
To implement the - Code Splitting: The Splitting of Code into chunks by route dimension or component so that it can be loaded on demand and take full advantage of the browser cache
- Extract the common third-party libraries: The SplitChunksPlugin plug-in performs the common module extraction, using the browser cache to cache the common code for a long time without frequent changes
7. Does CSS load block?
First, conclusion:
- CSS loading does not block DOM tree parsing
- CSS loading blocks rendering of the DOM tree
- The CSS load blocks the execution of the js statement that follows
To prevent the user from seeing a long period of white screen time, we should try to speed up CSS loading as much as possible. For example, we can use the following methods:
- Use CDN(because CDN will select the nearest node with cached content to provide resources for you based on your network condition, thus reducing load time)
- Compress CSS (with various packaging tools such as Webpack,gulp, etc., or by enabling gZIP)
- Use caches wisely (cache-control,expires, and e-tag are all fine, but you need to avoid the effects of caching when the file is updated. One solution is to add a version number after the file name.)
- Reduce the number of HTTP requests, combine multiple CSS files, or simply write inline (one of the disadvantages of inline is that it cannot be cached)
The principle of analytic
The browser rendering process is as follows:
- HTML parse files to generate DOM Tree, parse CSS files to generate CSSOM Tree
- Create a Render Tree by combining Dom Tree with CSSOM Tree
- Render the pixels to the screen according to the Render Tree.
We can see from the process:
- DOM parsing and CSS parsing are parallel processes, so this explains why CSS loading does not block DOM parsing.
- However, since the Render Tree is dependent on the DOM Tree and the CSSOM Tree, he must wait until the CSSOM Tree is built and the CSS resources are loaded (or failed to load the CSS resources) before he can Render. Therefore, CSS loading blocks Dom rendering.
- Since JS can manipulate previous Dom nodes and CSS styles, browsers maintain the order of CSS and JS in HTML. As a result, the stylesheet is loaded and executed before any subsequent JS execution. So the CSS blocks the subsequent js execution.
8. What are memory leaks? What causes this?
Memory leak explanation: the program has been dynamically allocated heap memory for some reason is not freed or cannot be freed.
- According to the JS garbage collection mechanism, memory will be reclaimed only when the number of references in memory is 0
- Objects in the global execution context are not released until they are marked as no longer in use
Several scenarios for memory leaks
- Too many global variables. Usually the variable is not defined or the global variable is referenced
Function a(){b=10; } a(); b++; SetTimeout (()=>{console.log(b)},1000)Copy the code
- Closure. Memory references left by mandatory packages are not resolved manually. By defining closures, you eliminate the side effects of closures.
function closuer (){ const b = 0; return (c)=> b + c } const render = closuer(); render(); render = null; // Set this parameter to NULL, and GC will clean it upCopy the code
- Event listening has not been removed
function addEvent (){ const node = document.getElementById('warp'); node.addEventListener('touchmove',()=>{ console.log('In Move'); }) } const onTouchEnd = (){ const node = document.getElementById('warp'); node. } useEffect(()=>()=>{ const node = document.getElementById('warp'); node.removeEventListener('touchmove'); <div id='warp' onTouchEnd={onTouchEnd}> // code... </div>)Copy the code
- The cache. You are advised to set the expiration time for all caches.
This article is from: github.com/febobo/web-… If there is infringement, contact delete
The last
We have more than 500 interview questions, covering HTML, CSS, JS, React, Vue, Node, etc. TypeScript, front-end security, algorithms, performance optimization, Design patterns, engineering, computer fundamentals, and more, with online answer tests. Finally, I wish the partner who will be interviewed to be the offer harvester ~