Interview questions

Comb front often meet test questions and answers.

A, web

Front-end performance optimization

Performance Rating Tool (PageSpeed or YSlow)

css

  • What are the methods of CSS optimization and performance improvement
  • Multiple CSS are merged to minimize HTTP requests
  • Place the CSS file at the top of the page
  • Remove an empty CSS rule
  • Avoid CSS expressions
  • Selectors are optimized for nesting to avoid being too deep
  • Make full use of CSS inheritance properties to reduce the amount of code
  • Abstraction extracts common styles, reducing the amount of code
  • When the attribute value is 0, the unit is not added
  • When the value of the property is a decimal less than 1, omit the 0 in front of the decimal point
  • Use CSS Sprites to assemble multiple images into a single image, and access the image content through the CSS Background property

js

  • Throttling, anti-shaking
  • Long list scrolling to visual area dynamic loading (Big data rendering)
  • Image loading lazy (data-src)
  • When using closures, manually remove unwanted local variables at the end of the function, especially if dom nodes are cached
  • DOM operation optimization
    • Add THE DOM in batches firstcreateElementCreate and add nodes, and finally add them to the DOM once
    • Batch bind events, useEvent delegationThe binding parent node implementation takes advantage of the event bubbling feature
    • If you can useinnerHTMLInstead ofappendChild
    • Try to add the class attribute when adding styles to the DOM, rather than using style to reduce rearrangements (Reflow)

network

  • Reduce the number of HTTP requests
  • Using the browser cache, common dependencies (such as Vue, Jquery, UI components, etc.) are packaged separately/as single files to avoid duplicate requests
  • reducecookieSize, use as much as possiblelocalStorageInstead of
  • CDN manages static files
  • The Gzip compression function is enabled

Browser kernel

  • It is divided into two parts: Layout Engineer or Rendering Engine and JS Engine

  • Rendering engine: Takes the content of a web page (HTML, XML, images, etc.), organizes information (such as adding CSS, etc.), and calculates how the page will be displayed, and outputs it to a monitor or printer. The kernel of a browser interprets the syntax of a web page differently, and therefore renders it differently. All Web browsers, E-mail clients, and other applications that need to edit and display web content require a kernel

  • The JS engine parses and executes javascript to achieve the dynamic effect of web pages

  • At first there was no clear distinction between the rendering engine and the JS engine. As the JS engine became more and more independent, the kernel tended to refer only to the rendering engine

What are the common browser kernels

  • TridentThe kernel:IE,MaxThon,TT,The World,360, sogou browser, etc. [also known as MSHTML]
  • GeckoThe kernel:Netscape6And above versions,FF,MozillaSuite/SeaMonkeyEtc.
  • PrestoThe kernel:Opera7And above. [OperaKernel originally: Presto, now:Blink; ]
  • WebkitThe kernel:Safari,ChromeAnd so on. [ChrometheBlink(WebKitBranch of)]

The difference between cookies, sessionStorage, localStorage, and indexDB

  • Cookies are data stored locally by websites to identify users
  • Whether HTTP requests can only be carried
    • Cookie data is always therehomologousIs carried in the HTTP request, cross-domain needs to be setwithCredentials = true
    • SessionStorage and localStorage do not automatically send data to the server. Data is stored locally
  • Storage size:
    • The size of cookie data cannot exceed4k;
    • SessionStorage and localStorage have storage size limits, but they are much larger than cookies and can be reached5MOr larger, depending on the browser size;
  • Valid time:
    • Cookie The cookie is valid until it expires, even if the window or browser is closed
    • LocalStorage The disk stores persistent data. Data is not lost after the browser is closed unless data is proactively deleted
    • SessionStorage Is stored in the memory. Data is automatically deleted after the current browser window closes

Chart comparison:

features cookie localStorage sessionStorage indexDB
Data lifecycle Usually generated by the server, you can set the expiration time It’s always there until it’s cleaned up Clean up when the page is closed It’s always there until it’s cleaned up
Data store size 4K 5M 5M infinite
Communicate with the server It is carried in the header each time and has an impact on request performance Don’t participate in Don’t participate in Don’t participate in

With cookies, you also need to pay attention to security:

attribute role
value If the value is used to save the user login state, it should be encrypted and the plaintext user ID cannot be used
http-only Can’t passJSaccessCookieTo reduceXSSattack
secure Only in the agreement forHTTPSIs carried in the request
same-site Specifies that browsers cannot be carried in cross-domain requestsCookieTo reduceCSRFattack

What happens between the time you enter the URL and the time the browser displays the page

  • Reference: What happens between entering the URL and the browser displaying the page

Understanding of AMD and CMD

  • CommonJS is a specification for server-side modules, which Node.js uses. The CommonJS specification loads modules synchronously, that is, only after the load is complete can the following operations be performed. The AMD specification loads modules asynchronously, allowing you to specify callback functions

  • The style recommended by AMD is to return an object as a module object, and the CommonJS style exposes module objects by assigning values to attributes of module.exports or exports

  • AMD

Es6 module CommonJS, AMD, CMD

  • CommonJSIn the specification of eachJavaScriptThe file is a separate module context (module context), properties created by default in this context are private. That is, variables defined in one file (including functions and classes) are private and not visible to other files.
  • CommonJSThe module is loaded synchronously and will cause congestion in the browser, so it is not applicable
  • AMDAsynchronous, callbacks need to be defineddefineway
  • es6A module is a separate file. All variables inside the file are not available externally. If you want the outside to be able to read a variable inside the module, you must useexportKeyword to output the variablees6You can also export classes and methods to automatically apply strict mode

Modularity (AMD, CMD, CommonJS, ES6)

The evolution of modularity

  • 1. File partition mode pollution global scope name conflict cannot manage module dependencies
  • 2. Namespace method: Based on the first stage, each module exposes only one global object and all variables are mounted to this global object
  • 3.IIFE executes functions immediately to provide private space for modules
  • This is the early way to land modularity without tools and specifications

Emergence of modularity specification Modularity specification + module loader

1. AMD asynchronous loading

  • Define (‘modle’, [load resource], ()=>{})
  • It’s complicated to use
  • The module JS file is frequently requested
  • Load dependencies first
// require. Js uses this style

define(['a.js'.'b.js'].function(A, B) {
    // do something
})


// Create a node with a script tag
var node = document.createElement('script')
node.type = 'text/javascript'
node.src = '1.js'

// 1.js after the onload event
node.addEventListener('load'.function(evt) {
    // Start loading 2.js
    var node2 = document.createElement('script')
    node2.type = 'text/javascript'
    node2.src = '2.js'
    // Insert the 2.js script node
    document.body.appendChild(node2)
})
// Insert the script node into the DOM
document.body.appendChild(node);
Copy the code

2. CMD sea.js

  • sea.js
  • According to the need to load
  • Execute 2.js as soon as require(‘2.js’) is encountered
define(function() {
    var a = require('2.js')
    console.log(33333)})Copy the code

3. Commonjs server specification

  • A file is a module
  • Each module has a separate scope
  • Exports members through module.exports
  • The modules are loaded through the require function
  • Commonjs issynchronousThe execution mechanism of node is to load modules at startup and not to load modules during execution
  • The CommonJS module outputs a copy of a value, and once it outputs a value, changes within the module cannot affect the value
  • CommonJS modules are loaded in the order in which they appear in the code
  • Because CommonJS loads modules synchronously, on the server side, the files are saved on the disk, so there is no problem with synchronous loading, but on the browser side, the files need to be requested from the server, so synchronous loading is not applicable, so CommonJS does not apply to the browser side.
  • The CommonJS module can be loaded multiple times, but is only run once on the first load, and then the result is cached, and later loads read the cached result directly. For the module to run again, the cache must be cleared

4. ESmodules

  • Modularity is implemented at the language level by setting type to Module in the script tag
  • The basic features
    • The strict mode is automatically adopted, and use strict is ignored
    • Each ESM module is a separate private scope
    • The ESM requests external JS modules through CORS
    • The script tag in the ESM delays the execution of the script
    • ES6 modules are dynamic references, and changes to reference type attributes affect each other
  • Export import Performs import and export
    • It is not the value of the member that is exported, but the memory address of the member that is exported
    • The ES Module can import CommonJS modules
    • The ES Module module cannot be imported into CommonJS
    • CommonJS always exports only one default member
    • Note that import is not deconstructing the exported object

Browser cache

Browser caches are divided into strong caches and negotiated caches. When a client requests a resource, the process for obtaining the cache is as follows

  • Let’s start with some of this resourcehttp headerCheck whether it matches the strong cache. If it does, the cache resource is directly obtained from the local server and no request is sent to the server.
  • When the strong cache misses, the client sends the request to the server, which passes through anotherrequest headerVerify that the resource matches the negotiated cache, calledhttpIf it matches, the server returns the request, but does not return the resource. Instead, it tells the client to get the resource directly from the cache. After receiving the return, the client will get the resource from the cache.
  • What strong caches and negotiated caches have in common is that the server does not return resources if the cache is hit; The difference is that the strong cache does not send requests to the server, but the negotiated cache does.
  • When the negotiation cache is also dead, the server sends the resource back to the client.
  • whenctrl+f5When the page is forcibly refreshed, it is loaded directly from the server, skipping the strong cache and negotiated cache.
  • whenf5When refreshing a web page, the strong cache is skipped, but the negotiated cache is checked.

Strong cache

  • Expires(This field ishttp1.0When, the value is an absolute timeGMTA time string in the format of the expiration time of the cached resource.
  • Cache-Control:max-age(This field ishttp1.1The specification of the strong cache uses itmax-ageValue to determine the maximum lifetime of the cached resource, which is valued in seconds.

Negotiate the cache

  • Last-Modified(The value is the last update time of the resource, which is returned with the server response. Even if the file is changed back, the date will change.)
  • If-Modified-Since(Compare the two times to determine whether the resource has been modified between the two requests, if not, the negotiated cache is matched)
  • ETagUnique identifier of resource content, delivered with the serverresponseReturn, based only on whether the contents of the file have changed)
  • If-None-MatchThe server compares the header of the requestIf-None-MatchWith the current resourceETagConsistency determines whether the resource has been modified between requests, and if not, the negotiation cache is matched)

How does a browser render a web page

  • Reference: Browser rendering page process

Repaint and Reflow

Redraw and backflow occur frequently when we set node styles and can greatly affect performance.

  • redraw: When a node needs to change its appearance without affecting its layout, e.g. changecolorIt’s called a redraw
  • Backflow: Layout or geometric properties that need to be changed are called backflow.
  • Backflow must result in redrawing, but redrawing does not necessarily cause backflow. The cost of backflow is much higher, and changing the children in the parent node is likely to lead to a series of backflow in the parent node.

The following actions can cause performance problems:

  • changewindowThe size of the
  • Change the font
  • Add or remove styles
  • Text change
  • Positioning or floating
  • The box model

Redraw and backflow are also related to Eventloop.

  • whenEventloopafterMicrotasksAfter, will judgedocumentDoes it need to be updated because the browser is60HzRefresh rate per16.6 msIt will only be updated once.
  • And see if there isresizeorscrollEvent, if there is one, it will trigger the event, soresizescrollEvents are also at least16msIs triggered once, and has its own throttling function.
  • Determine if it’s triggeredmedia query
  • Update the animation and send the event
  • Check whether full-screen operation events exist
  • performrequestAnimationFrameThe callback
  • performIntersectionObserverCallback, which is used to determine whether an element is visible, can be used on lazy loads, but is not compatible with updating the interface
  • So that’s what you might do in one frame. If there is idle time in a frame, it will executerequestIdleCallbackThe callback

How to reduce redrawing and reflux:

  1. usetransformalternativetop
  2. usevisibilityreplacedisplay: noneBecause the former only causes redrawing, the latter causes backflow (changes the layout)
  3. Do not put attribute values of nodes in a loop as variables in the loop
  4. Don’t usetableLayout, perhaps a small change can cause the entiretableRelayout of
  5. Animation speed to achieve the choice, the faster the animation speed, the more reflux times, can also choose to userequestAnimationFrame
  6. CSSThe selector matches from right to left to avoid too many layers of nodes
  7. A node that is frequently redrawn or reflow is set to a layer. The layer prevents the rendering behavior of that node from affecting other nodes. Such as forvideoIn the case of a label, the browser automatically turns the node into a layer.
  8. Avoid the use ofcssExpressions (expression) because the value is recalculated on each call (including loading the page)
  9. Try to usecssProperty shorthand, e.gborderInstead ofborder-width.border-style.border-color
  10. Modify element styles in batches:elem.classNameelem.style.cssTextInstead ofelem.style.xxx
  11. When you need to perform complex operations on an element, you can hide it (display:"none") and will be displayed after the operation is completed
  12. You need to create multipleDOMNode is usedDocumentFragmentAfter the creation, add it to the system oncedocument
  13. The cacheLayoutAttribute values, such as:var left = elem.offsetLeft;So, multiple useleftOnly one reflux is produced

There are many ways to set a node to a layer. You can create a new layer using the following common properties

  • will-change
  • video,iframeThe label

Optimizes the first screen loading

  1. Vue-router route lazy loading (using Webpack code cutting)
  2. CDN acceleration is used to extract generic libraries from vendors
  3. Nginx gZIP compression
  4. Vue Asynchronous component
  5. Server-side render SSR
  6. If you are using some UI libraries, load on demand
  7. Webpack starts gZIP compression
  8. If the first screen is the login page, it can be made into multiple entries
  9. Lazy image loading reduces network bandwidth usage
  10. The page uses a skeleton screen
  11. Take advantage of the async and defer properties of the script tag. The async property can be added to js files that are functionally independent and do not require immediate execution. If it’s a low-priority JS with no dependencies, add the defer attribute.

availableperformance.timingSee how long each step takes: White screen time:performance.timing.responseStart - performance.timing.navigationStart

Second, the HTML

What new features and elements have been removed from HTML5?

New features: HTML5 is no longer a subset of SGML, it’s all about graphics, location, storage, multitasking, etc

  • New selector document. QuerySelector, document. QuerySelectorAll
  • Drag and Drop API
  • The video and audio of the media
  • LocalStorage localStorage and sessionStorage
  • Offline Application Manifest
  • Desktop Notifications
  • Semantic tags article, footer, Header, nav, section
  • Enhanced form controls calendar, date, time, email, URL, and search
  • Geolocation
  • Multitasking webworker
  • Full-duplex communication protocol Websocket
  • History Management History
  • Cross-domain resource sharing (CORS) access-control-allow-Origin
  • Page visibilitychange event visibilitychange
  • PostMessage communication across Windows
  • The Form Data object
  • Canvas painting

Removed elements:

  • Pure expressive elements: Basefont, BIG, Center, FONT, S, strike, TT, U
  • Elements that negatively affect usability: Frame, Frameset, noframes

viewport

<meta name="viewport" content="Width = device - width, initial - scale = 1.0, the minimum - scale = 1.0, the maximum - scale = 1.0, user - scalable = no" />
<! -- width sets the viewport width to a positive integer, or string 'device-width' device-width device width height Sets the viewport height. Initial-scale can be set to a number with a decimal value. Minimum-scale can be set to a number with a minimum value. Maximum-scale can be set to a number with a maximum value. • Scalable scalable scalable scalable scalable scalable Scalable Scalable Scalable Scalable Scalable Scalable Scalable Scalable scalable Scalable Scalable Scalable Scalable Scalable Scalable Scalable Scalable Scalable Scalable Scalable Scalable Scalable Scalable Scalable Scalable Scalable Scalable Scalable Scalable Scalable Scalable
Copy the code

Extended question: How do you handle the problem of rendering 1px to 2px on mobile?

  • Local processing
    • The viewport attribute in the meta tag is set to 1
    • Rem can be performed according to the design draft standard, and the scale(0.5) of Transfrome can be doubled.
  • Global processing
    • The viewport attribute in the mate tag with the initial scale set to 0.5
    • Rem can go according to the design standard

HTML document parsing

  • Reference: HTML documents are parsed into AST syntax trees

Three, CSS,

1. CSS selector priority

! important > inline > id > class > tag > * > inherit > default

  • ! Important: greater than others
  • Industry: 1000
  • Id selector: 100
  • Classes, pseudo-classes, and property selectors such as.content: 10
  • Type selectors and pseudo-element selectors: 1
  • Wildcard, sub-selector, adjacent selector: 0

Those written after the same level have higher priority.

The same class style in CSS takes precedence over the class name in HTML

2. Center horizontally and vertically

  • The text is centered horizontally:text-algin: center
  • The text is centered vertically:line-heightIs equal to the containerheight;display: flex; algin-items: center;
  • Div is horizontally centered:
    1. margin: 0 auto;
    2. Margin-left: width / 2; margin-left: width / 2; transform: tranlateX(-50%)
    3. Unknown parent element width: position: Absolute: top: 50%; transform: tranlateY(-50%)
    4. display: flex; justify-content: center;
  • Div vertical center:
    1. Margin-top: height / 2; margin-top: height / 2; transform: tranlateY(-50%)
    2. Unknown parent height: position: Absolute: top: 50%; transform: tranlateY(-50%)
    3. display: flex; algin-items: center;

3. Remove the inline-block gap

  • Remove the blank space
  • Use margin negative
  • Use the font – size: 0
  • letter-spacing
  • word-spacing

4. Clear the float

Floating effects: (1) due to the floating elements from the document flow, so the height of the parent element cannot be open, has affected the parent element size and element (2) with the floating element at the same level of the floating element will follow, because the floating elements from the document flow is not the original position (3) if the floating element is not the first to the floating element, Then the elements before this element also need to float, otherwise the structure of the page is likely to be affected.

  1. useclear: bothRemove the floating

Put an empty div tag after the float element, div style clear:both to clear the float. It has the advantages of simplicity, convenience and good compatibility, but it is generally not recommended to use this method, because it will cause structural chaos and is not conducive to later maintenance.

  1. Using pseudo-elementsafterTo clear the float

The after pseudo-element is added to the parent element, which can support the height of the parent element by clearing the float of the pseudo-element

.clearfix:after{
    content: "";
    display: block;
    visibility: hidden;
    clear: both;
}
Copy the code
  1. Using CSSoverflowattribute

When the parent element is set to overflow style, either overflow:hidden or overflow:auto can clear the float as long as its value is not visible. Its essence is to construct a BFC, so that it can achieve the effect of supporting the parent element

  • Reference: Clear the float of the CSS

5. Margin overlap

The spacing between the two elements in the vertical direction of the layout is not equal to the sum of margin, but the larger one is taken

  1. Sibling adjacent element

Margin-bottom: 20px for the upper element and margin-top: 20px for the lower element 10px, the actual spacing is 20px. How to avoid this: do not set the same siblings at the same time, but set either a margin-bottom or a margin-top, or set the padding

  1. Father and son elements

< span style = “box-sizing: border-box; color: RGB (74, 74, 74); line-height: 20px; font-size: 13px! Important; white-space: normal;” Or trigger the BFC

6. Three-column layout

Requirements: left and right fixed width, middle adaptive

  1. float
<style>
.left{
    float: left;
    width: 300px;
    height: 100px;
    background: #631D9F;
}
.right{
    float: right;
    width: 300px;
    height: 100px;
    background: red;
}
.center{
    margin-left: 300px;
    margin-right: 300px;
    background-color: #4990E2;
}
</style>
<body>
    <div class="left">On the left</div>
    <div class="right">right</div>
    <div class="center">In the</div>  
    <! If center is in the middle, right will be pushed to the next row by the elements in the middle block -->
</body>
Copy the code
  1. position
<style>
.left{
    position: absolute;
    left: 0;
    width: 300px;
    background-color: red;
}
.center{
    position: absolute;
    left: 300px;
    right: 300px;
    background-color: blue;
}
.right{
    position: absolute;
    right: 0;
    width: 300px;
    background-color: #3A2CAC;
}
</style>
<body>
    <div class="left">On the left</div>
    <div class="center">In the</div>  
    <div class="right">right</div>
</body>
Copy the code
  1. flex
<style>
.main {
    display: flex;
}
.left{
    width: 300px;
}
.center{
    flex-grow: 1;
    flex-shrink: 1;
}
.right{
    width: 300px;
}
</style>
<body class="main">
    <div class="left">On the left</div>
    <div class="center">In the</div>  
    <div class="right">right</div>
</body>
Copy the code

7. BFC

The BFC stands for Block Formatting Context, which is a rendering area used to lay out Block boxes.

In simple terms, the BFC is actually an area where certain rules are followed, a unique set of rendering rules.

In fact, document flow is divided into three types: normal flow, positioning flow and floating flow. Normal flow actually refers to FC in BFC, that is, formatting context.

Normal flow: Elements are laid out from top to bottom and left to right according to their chronological position in HTML, in which inline elements are arranged horizontally until the block-level elements are rendered as a complete new line when the line is full and then newlines.

Formatting context: a rendered area of a page that has a set of rendering rules that determine how its children are laid out and how they relate to and function with other elements

§ Rules of THE BFC: 1) Margins of elements in the BFC region overlap. 2) Elements in the BFC region do not overlap with floating elements. 3) When calculating the height of THE BFC region, the floating element is also involved in the calculation. 4) THE BFC region is equivalent to a container. The internal elements will not affect the external elements, and the external elements will not affect the internal elements.

§ Application of BFC:

  1. Clear float: parent element set overflow: hidden trigger BFC to achieve clear float, prevent the parent element height collapse, the following elements are overwritten, realize text surround, etc.
  2. Eliminate vertical margin overlap between adjacent elements: Layer the second child element and set overflow: hidden to build the BFC so that it does not affect the external elements.
  3. Eliminate the parent element margin overlap, parent element set overflow: hidden

§ Ways to trigger BFC:

  1. Float is not none, and the region where the floating element resides is a BFC region.
  2. The area where the value of position is either static or relative is a BFC area
  3. The area where table cell elements whose display is table-cell are located is also a BFC area
  4. The area where elements whose Overflow is not visible are located is also a BFC area
  • Reference: CSS you should know the BFC

8. Flex layout

Flexible layout, Flex layout will become the layout of choice in the future. Compatibility:

  1. Webkit kernel browsers must be prefixed with -webkit.
  2. Internet explorer does not support

Basic concepts:

  1. Containers & Projects: Elements laid out in Flex are called Flex Containers, or “containers” for short. All of its child elements automatically become members of the container and are called Flex items, or “projects” for short.
  2. Spindle & cross axis: the direction of the stack. By default, the spindle is horizontal and the cross axis is vertical. throughflex-derection: columnSet the main axis to vertical.

Container properties:

  • display: flex
  • The flex – direction: the direction of the spindle (orientation) of the project, the row | row – reverse | column | column – reverse;
  • The flex – wrap: whether a newline, nowrap | wrap | wrap – reverse;
  • Flex-flow: short for direction and wrap
  • The justify – the content: the main shaft alignment, flex – start | | flex – end center | space – between | space – around;
  • The align – items: cross shaft alignment, flex – start | flex – end | center | baseline | stretch;
  • Align-content: Alignment of multiple axes. This property does not work if the project has only one axis. flex-start | flex-end | center | space-between | space-around | stretch;

Attributes of the project:

  • Order: The order in which items are arranged. The smaller the value, the higher the order. The default value is 0.

  • Flex-grow: Scale, which defaults to 0, specifies the proportion of the remaining space that an element is allocated.

  • Flex-shrink: Shrink scale, which defaults to 1, specifies the size of the shrink to which an element is assigned.

  • Flex-basis: The main space occupied by the project before excess space is allocated. Default is auto

  • Flex: short for grow, shrink, and basis. Default is 0, 1 auto

  • The align – self: a single project different alignment, the default value is auto, auto | flex – start | flex – end | center | baseline | stretch;

  • Flex Layout Tutorial: Syntax – Ruan Yifeng

9. The CSS animations

例 句 : Changes are slowly executed over a set length of time, rather than immediately.

The real point of delay is that it specifies the order in which the animation takes place, allowing multiple different transitions to be linked together to create complex effects.

The value transition is abbreviated, and the extension is:

  1. Transition-property: indicates the transition property
  2. Transition-duration: indicates the transition duration
  3. Transition -delay: indicates a delay of several seconds
  4. transition-timing-function
    • At a constant speed linear:
    • Ease – in: accelerated
    • Ease – out: slow down
    • Cubic bezier functions: Custom speed modes, and the last cubic Bezier, can be customized using the tools website.
/* Change in 1s transition */
transition: 1s;
/* Specifies the transition property */
transition: 1s height;
/* Specifies that multiple attributes transition at the same time */
transition: 1s height, 1s width;
/* Specifies the delay time */
transition: 1s height, 1s 1s width;
/* Specifies the speed of state change */
transition: 1s height ease;
/* Specifies the speed of custom state change */
transition: 1s height cubic-bezier(.83.97.05.1.44);
Copy the code

Transition has the advantage of being simple and easy to use, but it has several big limitations.

  1. Transition requires an event to be triggered, so it can’t happen automatically when a web page loads.
  2. The transition is a one-time event, and it can’t happen again unless it’s triggered again and again.
  3. Transition can only define a start state and an end state. It cannot define an intermediate state, which means there are only two states.
  4. A transition rule can only define the change of one property, not more than one property.

CSS Animation is proposed to solve these problems.

  • Transition + Transform = Animation for two key frames
  • Animation emphasizes flow and Control, Duration + TransformLib + Control = Animation of multiple key frames

2. Animation animation

.element:hover {
  animation: 1s rainbow;
  /* animation: 1s rainbow infinite; Animation: 1s rainbow 3; Specifies the number of animations to play */
}

@keyframes rainbow {
  0% { background: #c00; }
  50% { background: orange; }
  100% { background: yellowgreen; }}Copy the code

< animation > < animation > < animation > < animation >

  1. Animation-name: Specifies the name of the @keyFrames that the animation will be defined with.
  2. Animation-duration: The duration of the entire animation.
  3. Animation-timing-function: Speed control for animation in progress, such as Ease or Linear.
  4. Animation-delay: animation delay time.
  5. Animation-direction: The direction in which the animation moves when it is repeated.
  6. Animation-iteration – Count: The number of times an animation loop is executed.
  7. Animation-fill-mode: sets the state of the animation after/before execution. For example, you can have the animation stay in the last scene after execution, or revert to the original state.
  8. Animation-play-state: pause/start the animation.
  • Reference: Introduction to CSS Animation

10. What are the methods of CSS optimization and performance improvement

  • Multiple CSS are merged to minimize HTTP requests
  • Place the CSS file at the top of the page
  • Remove an empty CSS rule
  • Avoid CSS expressions
  • Selectors are optimized for nesting to avoid being too deep
  • Make full use of CSS inheritance properties to reduce the amount of code
  • Abstraction extracts common styles, reducing the amount of code
  • When the attribute value is 0, the unit is not added
  • When the value of the property is a decimal less than 1, omit the 0 in front of the decimal point
  • The CSS Sprite figure

Four, javascript,

  • Reference: javascript interview questions

Five, the vue

  • Reference: VUE interview questions collation

Six, webpack

  • webpackWebpack is a module packaging tool that you can use to manage yourModule is dependent onAnd,Compilation of outputStatic files required by modules.
  • It manages and packages HTML, Javascript, CSS, and all kinds of static files (images, fonts, etc.) used in Web development, making the development process more efficient.
  • Webpack has corresponding module loaders for different types of resourcesloader.
  • The WebPack module packer analyzes the dependencies between modules and generates optimized and merged static resources.
  • Its plug-in functionality provides lifecycle hooks for handling various files, enabling developers to leverage the plug-in functionality to develop many custom features.

1. The articles I’ve written about WebPack

  • Webpack Packaging Principles & handwritten WebPack core packaging process
  • Add mock middleware to webpack-dev-server to implement front-end data emulation
  • Detailed description of common WebPack configurations
  • Webpack configuration optimization

2. Overview of core packaging principles

3. Loader

Write a loader:

Loader is a node module that outputs a function. This function is called when a resource needs to be converted by the loader. In addition, this function can access the Loader API through the this context provided to it. Reverse – TXT – loader.

Parse order: bottom up, right to left

/ / define
module.exports = function(src) {
    // SRC is the content of the original file (abcde), and the next step is to process the content, here is the inversion
    var result = src.split(' ').reverse().join(' ');
    // Return the JavaScript source code, which must be a String or Buffer
    return `module.exports = '${result}'`;
}
/ / use
{
    test: /\.txt$/,
    loader: 'reverse-txt-loader'
}
Copy the code

4. Configuration examples

§ base

module.exports = {
    entry: {
        app: './src/main.js'
    },
    output: {
        path: path.resolve(__dirname, '.. /dist'),
        filename: '[name].js'.publicPath: ' '
    },
    resolve: {
        extensions: ['.js'.'.vue'.'.json'.'.css'.'.less'].alias: {
            The '@': resolve('src'),
            src: resolve('src'),
            static: resolve('static')}},module: {
        rules: [{test: /\.vue$/,
                loader: 'vue-loader'.options: vueLoaderConfig
            },
            {
                test: /\.js$/,
                loader: 'babel-loader'.include: [resolve('src'), resolve('test')]}, {test: /\.(png|jpe? g|gif|svg)(\? . *)? $/,
                loader: 'url-loader'.query: {
                    limit: 1.name: utils.assetsPath(`img/[name].[ext]`)},include: /nobase64/
            },
            {
                test: /\.svg(\? \S*)? $/,
                loader: 'svg-sprite-loader'.query: {
                    prefixize: true.name: '[name]-[hash]'
                },
                include: [resolve('src')].exclude: /node_modules|bower_components/}},plugins: [
        new VueLoaderPlugin(),
        new ProgressBarPlugin({
            format: 'build [:bar] ' + chalk.green.bold(':percent') + ' (:elapsed seconds) : (:msg)'.clear: false.width: 60}})];Copy the code

§ dev

var path = require('path');
var utils = require('./utils');
var webpack = require('webpack');
var config = require('.. /config');
var merge = require('webpack-merge');
var baseWebpackConfig = require('./webpack.base.conf');
var CopyWebpackPlugin = require('copy-webpack-plugin');
var MyPlugin = require('./htmlPlugin');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var MiniCssExtractPlugin = require('mini-css-extract-plugin');
var OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin');

module.exports = merge(baseWebpackConfig, {
    mode: 'development'.externals: {
        vue: 'Vue'
    },
    devtool: '#source-map'.output: {
        path: config.build.assetsRoot,
        filename: utils.assetsPath(`js/[name].js`),
        chunkFilename: utils.assetsPath(`js/[name].js`)},plugins: [
        new webpack.HotModuleReplacementPlugin(),
        new FriendlyErrorsPlugin(),
        new CopyWebpackPlugin([
            {
                from: path.resolve(__dirname, `.. /static`),
                to: path.resolve(config.dev.assetsPublicPath, `/dist/static`)}]),new HtmlWebpackPlugin({
            alwaysWriteToDisk: true.filename: 'index.html'.template: path.resolve(__dirname, `.. /src/index.html`), // Template path
            inject: false.excludeChunks: [].baseUrl: ' '.currentEnv: 'development'.envName: 'local'.curentBranch: ' '
        }),
        new HtmlHardDisk()
    ],
    optimization: {
        /* This plugin is in mode: Production is always enabled by default so that it is also enabled during development https://webpack.js.org/configuration/optimization/#optimizationconcatenatemodules */
        concatenateModules: true.splitChunks: {
            cacheGroups: {
                commons: {
                    test: /[\\/]node_modules[\\/]/,
                    name: 'vendors'.chunks: 'all'
                },
                styles: {
                    name: 'styles'.test: /\.css$/,
                    chunks: 'all'.enforce: true}}},runtimeChunk: {
            name: 'manifest'
        },
        minimizer: [
            // Code compression UglifyJsPlugin upgrade
            new TerserPlugin({
                cache: true.parallel: true.terserOptions: {
                    sourceMap: true.warnings: false.compress: {
                        // warnings: false
                    },
                    ecma: 6.mangle: true
                },
                sourceMap: true
            }),
            new OptimizeCSSPlugin({
                cssProcessorOptions: {
                    autoprefixer: {
                        browsers: 'last 2 version, IE > 8'}}})Copy the code

§ prod

var path = require('path');
var utils = require('./utils');
var webpack = require('webpack');
var merge = require('webpack-merge');
var baseWebpackConfig = require('./webpack.base.conf');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin');
var CopyWebpackPlugin = require('copy-webpack-plugin');
var HtmlHardDisk = require('html-webpack-harddisk-plugin');
var MiniCssExtractPlugin = require('mini-css-extract-plugin');
var OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin');

module.exports = merge(baseWebpackConfig, {
    mode: 'production'.externals: {
        vue: 'Vue'
    },
    output: {
        path: config.build.assetsRoot,
        filename: utils.assetsPath(`js/[name].js`),
        chunkFilename: utils.assetsPath(`js/[name]-[chunkhash].js`)},plugins: [
        // http://vuejs.github.io/vue-loader/en/workflow/production.html
        new webpack.DefinePlugin({
            'process.env': env
        }),
        // extract css into its own file
        new MiniCssExtractPlugin({
            filename: utils.assetsPath('css/[name].css'),
            allChunks: true
        }),
        // copy custom static assets
        new CopyWebpackPlugin([
            {
                from: path.resolve(__dirname, `.. /static`),
                to: path.resolve(__dirname, `.. /dist/static`)}]),new HtmlWebpackPlugin({
            alwaysWriteToDisk: true.filename: 'index.html'.template: path.resolve(__dirname, `.. /src/index.html`), // Template path
            inject: false.baseUrl: ' '.currentEnv: 'production'.envName: 'prod'.curentBranch: ' '
        }),
        new BundleAnalyzerPlugin()
    ],
    optimization: {
        minimizer: [
            // Code compression UglifyJsPlugin upgrade
            new TerserPlugin({
                // cache: true,
                parallel: true.terserOptions: {
                    warnings: false.compress: {},// ecma: 6,
                    mangle: true
                },
                sourceMap: true
            }),
            new OptimizeCSSPlugin({
                cssProcessorOptions: {
                    autoprefixer: {
                        browsers: 'last 2 version, IE > 8'}}})].splitChunks: {
            cacheGroups: {
                commons: {
                    test: /[\\/]node_modules[\\/]/,
                    name: 'vendors'.chunks: 'all'}}},runtimeChunk: {
            name: 'manifest'}}};Copy the code

5. Manual Chungk subcontracting

  • Optimization. SplitChunks (before 4, CommonsChunkPlugin)

  • The vUE route is loaded lazily

6. Pack faster

  • Devtool’s sourceMap is time-consuming
  • The development environment does not perform meaningless operations, such as code compression, directory content cleaning, file hash calculation, and CSS file extraction
  • Third party dependency external link script introduction: VUE, UI components, JQuery, etc
  • HotModuleReplacementPlugin: hot update incremental builds
  • DllPlugin& DllReferencePlugin: Dynamically linked library to improve packaging efficiency, packaging third party modules only once and repackaging business code only on each build.
  • Thread-loader,happypack: multithreaded compilation to speed up compilation
  • NoParse: No need to parse dependencies of certain modules
  • Babel-loader Enables cache
  • SplitChunks (older versions with CommonsChunkPlugin) : Extract the common modules, package the modules that match the reference count (minChunks) together, and utilize the browser cache
  • Static analysis of code based on the modular system provided by ES6, removing dead code from the code during compression, reducing the size of the code.

7. Packaging volume optimization idea

  • The Webpack-bundle-Analyzer plug-in allows you to visually view the size of webpack files so that you can locate large files and optimize their size
  • Extracting third-party libraries or importing third-party libraries by referring to external files
  • Code compression plug-inUglifyJsPlugin
  • Gzip compression is enabled on the server
  • Load resource files on demandrequire.ensure=
  • strippingcssFile, packaged separately
  • Remove unnecessary plug-ins and use different configuration files for the development and production environments
  • SpritesmithPlugin: package multiple small images into one and control the display part using background-image, backgroud-pisition, width, height
  • The url-loader file size smaller than the set size is changed to base-64 encoded text, and the size and size are copied to the target directory by file-Loader

The Tree is Shaking

Background: In a project, there is an entry file, which is equivalent to the trunk of a tree. The entry file has many dependent modules, which are equivalent to branches. In practice, you rely on a module but only use some of its functionality. With tree-shaking, modules that are not in use are shaken off to remove useless code.

Idea: A technique for static analysis of code and removal of dead code based on the module system provided by ES6. Therefore, using Tree Shaking technology makes it easy to optimize our code and reduce the code volume.

Tree Shaking is based on the rollup implementation.

Based on the module system provided by ES6, WebPack performs static analysis on the dependency tree of the code, and marks import and export as 3 classes:

  • All imports are marked /* harmony import */
  • Harmony export([type])/ harmony export([type])/
  • /* unused harmony export [FuncName] */, where FuncName [FuncName] is the name of the export method, Uglifyjs (or other similar tool) is used to delete the code.

Why based on ES6 module implementation (ES6 Module features:

  • Appears only as a statement at the top level of the module
  • Import module names can only be string constants
  • Import binding is immutable

Condition:

  1. First, the source code must comply with the ES6 module specification (import & export), if the CommonJS specification (require) is not available.
  2. Code written in modules cannot have side effects, and if external variables are changed inside the code, they will not be removed.

Configuration method:

  1. Add a property to package.json:
{
    // if sideEffects is set to false, webpack will assume that all functions that are not used have no sideEffects.
    "sideEffects": false.// Set the blacklist to prevent deleting code by mistake
    "sideEffects": [
        // Listing the blacklist in the array, forbidding shaking the following code
        "@babel/polly-fill"."*.less".// Other modules with side effects
        "./src/some-side-effectful-file.js"],}Copy the code

Tree-shaking shakes unused code from the code and automatically turns it on in production mode

Tree-shaking is not a configuration option in WebPack, it is an optimization of a set of features used together and automatically started in production mode

// In development mode, set usedExports: true. When packaging, only the modules that are not in use will be marked. This may affect the accuracy of source-map tag locations.
{
    mode: 'develpoment'.optimization: {
        // Optimize the exported module
        usedExports: true}},// In production mode usedExports: true is enabled by default, and unused code will be removed during compression
{
    mode: 'production'.// The purpose of this property is to centrally configure optimization functions within WebPack
    optimizition: {
        // Only export externally used module members responsible for marking dead leaves
        usedExports: true.minimize: true.// The automatic compression code is responsible for shaking off the dead leaves
        /** * WebPack packs a module into a single closure by default ** The new API in WebPack 3 puts all modules into a single function, combining as many modules as possible, * increasing efficiency, reducing size and increasing scope */
        concatenateModules: true,}}Copy the code

Precautions for tree shaking:

  1. Write code using ES6 module syntax
  2. Utility class functions should be output as individual functions, not grouped into one object or class
  3. The statement sideEffects
  4. Be aware of side effects when you refactor your code yourself

Using babel-Loader to process JS code causes Tree-shaking to fail

  • The premise of treeshaking must be the code organized by the ES Module, that is, the code given to the ESMOdule must be the ESM. It is possible to convert the ESM to the CommonJS specification after we use babel-Loader to process the JS code (PRESET -env will be used when the plug-in works ESM => Coommonjs)

Solution: Configure preset-env modules: false to ensure that automatic conversion is not enabled (in the latest babel-Loader version, the conversion to commonJS is disabled automatically)

presets: [
    ['@babel/preset-env', {module: 'commonjs'}]]Copy the code

9. Brief introduction of common plug-ins

  • webpack-dev-server
  • Clean-webpack-plugin: cleans the output directory before compilation
  • CopyWebpackPlugin: copies files
  • HotModuleReplacementPlugin: hot update
  • ProvidePlugin: global variable setting
  • DefinePlugin: Defines global constants
  • SplitChunks (older versions with CommonsChunkPlugin) : Extract common modules and package together modules that match the number of references
  • Mini-css-extract-plugin: The CSS is packaged separately
  • TerserPlugin (older versions use UglifyJsPlugin) : Compresses code
  • Progress-bar-webpack-plugin: compilation progress bar
  • DllPlugin& DllReferencePlugin: Improve packaging efficiency by packaging third-party modules only once
  • Webpack-bundle-analyzer: Visualizes the size of webpack files
  • Thread-loader,happypack: multiprocess compilation to speed up compilation

nodejs

1. I wrote nodeJS related articles

  • Koa + MonGONDB to achieve user login registration module
  • Nodejs’s FS module callback style asynchronous operations are converted to promise and await style

2. Common nodeJS modules

  • path
  • fs
  • HTTP, url
  • express
  • koa
  • mongoose
  • process
  • cookie, session
  • Crypto related
  • os

3. Koa middleware idea, onion model

class Middleware {
    constructor() {
        this.middlewares = [];
    }
    use(fn) {
        if(typeoffn ! = ='function') {
            throw new Error('Middleware must be function, but get ' + typeof fn);
        } 
        this.middlewares.push(fn);
        return this;
    }
    compose() {
        const middlewares = this.middlewares;
        return dispatch(0);
        function dispatch(index) {
            const middleware = middlewares[index];
            if(! middleware) {return; }try{
                const ctx = {};
                const result = middleware(ctx, dispatch.bind(null, index + 1));
                return Promise.resolve(result);
            } catch(err) {
                return Promise.reject(err); }}}}/ / use
const middleware = new Middleware();
middleware.use(async (ctx, next) => {
    console.log(1);
    await next();
    console.log(2);
});
middleware.use(async (ctx, next) => {
    console.log(3);
    await next();
    console.log(4);
});
middleware.compose();// 1, 3, 4, 2

Copy the code

4. The difference between Express and KOA

  1. Encoding style: Express uses callback function style, KOA1 uses generator, KOA2 (default) uses await, more elegant style, KOA is more closely combined with ES6,7;
  2. Error handling: Express adopts the error-first handling method in the callback, deep exception can not be caught, so errors must be handled in each layer of callback, KOA uses try catch to catch errors, error uploading can be unified error handling;
  3. Koa removed the built-in router, View and other features from Express to make the framework itself more lightweight.
  4. The Express community is large and relatively well-documented, while the KOA community is relatively small;

network

1. Network Layer 7 Protocol (OSI model)

OSI is a well-defined set of protocol specifications, with many optional parts that accomplish similar tasks. It defines the hierarchy of an open system, the relationships between the layers, and the possible tasks that each layer contains, serving as a framework to coordinate and organize the services provided by the layers.

The OSI reference model does not provide a means of implementation, but rather describes concepts that can be used to coordinate the development of interprocess communication standards. That is, the OSI reference model is not a standard, but rather a conceptual framework to be used when developing standards.

  • Layer 7: Application layer

The Application Layer provides interfaces designed for Application software to set up communication with another Application. For example, HTTP, HTTPS, FTP, Telnet, SSH, SMTP, and POP3.

  • Layer 6 represents the layer

The Presentation Layer converts data into a format that is compatible with the receiver’s system format and suitable for transmission.

  • Layer 5 session layer

The Session Layer is responsible for setting up and maintaining the communication connection between two computers in a computer network during data transmission.

  • Layer 4 transport layer

The Transport Layer adds a Transport header (TH) to the data to form a packet. The transport header contains the transmission information such as the protocol used. For example, transmission Control Protocol (TCP).

  • Layer 3 Network layer

The Network Layer determines the routing and forwarding of data, adding Network table headers (NH) to packets to form groups. The network header contains network information. For example, Internet Protocol (IP) and so on.

  • Layer 2 Data link layer

The Data Link Layer is responsible for network addressing, error detection, and error correction. When a table header and a table tail are added to a packet, a Data Frame is formed. The datalock header (DLH) contains the physical address and methods for error detection and correction. A datalink tail (DLT) is a string indicating the end of a packet. Examples include Ethernet, wireless Local area Network (Wi-Fi), and General Packet Wireless Service (GPRS).

There are two sub-layers: the Logical Link Control (LLC) sub-layer and the Media Access Control (MAC) sub-layer.

  • Physical layer 1

The Physical Layer sends Data frames over the local area network (LAN). It is responsible for managing the communication between computer communication devices and network media. This includes pins, voltages, cable specifications, hubs, Repeaters, network cards, host interface cards, etc.

2. TCP three-way handshake

  • Client throughSYNThe segment sends a connection request to determine whether the server has enabled port preparation for connection. Status set toSYN_SEND;
  • If the server has an open port and decides to accept a connection, it returns oneSYN+ACKSegment to the client, and the status is set toSYN_RECV;
  • Description The client received the packet from the serverSYN+ACKPacket segment, which is sent to the serverACKSegment indicates acknowledgement. In this case, both the client and server are set toESTABLISHEDState. Connection established, ready to start data transfer.

Client: Can you receive my message? Server: Yes, can you receive my reply? Client: Ok, let’s get down to business.

Why three times? : Avoid historical connection, confirm the client sent the request is this communication person why not 4 times? : Three times is enough for the fourth waste

3. TCP waves four times

  1. Why not twice?
    • In two cases, the client immediately disconnects and no longer receives the disconnection message. It is not possible to confirm whether the server has received the disconnection message, but the server may still have incomplete messages.
  2. Why not three times?
    • In three cases, the server receives the disconnection message and sends an acknowledgement message to the client, but the client does not reply to the final confirmation of disconnection.

http

1. Structure of HTTP request packets

  1. The first Line is request-line including: Request method, Request URI, protocol version, CRLF
  2. The first line is followed by several lines of request headers, including general-header, request-header, or entity-header, each ending with CRLF
  3. There is a CRLF separation between the request header and the message entity
  4. It may contain a message entity depending on the actual request. An example of a request message is as follows:
GET/separate Protocols/rfc2616 rfc2616 - sec5. HTTP / 1.1 HTML Host: www.w3.org Connection: keep alive - cache-control: max-age=0 Accept: text/html,application/xhtml+xml,application/xml; Q = 0.9, image/webp, * / *; Q =0.8 User-agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) https://www.google.com.hk/ Accept-Encoding: gzip,deflate,sdch Accept-Language: zh-CN,zh; Q = 0.8, en. Q = 0.6 cookies: authorstyle = yes If - None - Match:"2cc8-3e3073913b100"
If-Modified-Since: Wed, 01 Sep 2004 13:24:52 GMT

name=qiu&age=25
Copy the code

2. Structure of the HTTP response packet

  • The first line is the status line including: HTTP version, status code, status description, followed by a CRLF
  • The first line is followed by several lines of response headers, including: general header, response header, and entity header
  • The response header and the response entity are separated by a CRLF blank line
  • Finally, an example of a possible message entity response message is shown below:
HTTP/1.1 200 OK
Date: Tue, 08 Jul 2014 05:28:43 GMT
Server: Apache/2
Last-Modified: Wed, 01 Sep 2004 13:24:52 GMT # Last modified time, used to negotiate the cache
ETag: "40d7-3e3073913b100" # File hash, used to negotiate caching
Accept-Ranges: bytes
Content-Length: 16599
Cache-Control: max-age=21600 # Strong cache (browser) maximum expiration time
Expires: Tue, 08 Jul 2014 11:28:43 GMT # Strong cache (browser) expiration time
P3P: policyref="http://www.w3.org/2001/05/P3P/p3p.xml"
Content-Type: text/html; charset=iso-8859-1

{"name": "qiu"."age"25} :Copy the code

3. Common HTTP status codes and their meanings

  • 1XX: indicates the information status code
    • 100 Continue This message is returned after the HTTP header has been sent. The server then sends the parameter information
  • 2XX: success status code
    • 200 OK A normal message is displayed
    • 201 Created The request succeeds and the server creates a new resource
    • 202 Accepted The server Accepted the request but has not yet processed it
  • 3XX: indicates redirection
    • 301 Moved Permanently to a new location.
    • 302 Found Temporary redirection.
    • 303 See Other Temporary redirects and always requests a new URI using GET.
    • 304 Not Modified The requested page has Not been Modified since the last request.
  • 4XX: Client error
    • 400 Bad Request The server does not understand the format of the Request. The client should not attempt to make the Request again with the same content.
    • 401 Unauthorized Requests Are not authorized.
    • 403 Forbidden Forbidden access.
    • 404 Not Found Failed to find how to match the resource URI.
  • 5XX: Server error
    • 500 Internal Server Error Indicates the most common Server Error.
    • 503 Service Unavailable The server is temporarily unable to process the request (possibly due to overload or maintenance).

4. Common Web security and protection

  • Reference: Common Web Attacks and Protection Methods

5. Differences between HTTP1.0, HTTP1.1, and HTTP2.0

§ http1.0 vs http1.1

  1. Persistent Connection: When the value of the Connection request header is keep-alive, the client notifts the server to return the request result to maintain the Connection, which can effectively reduce the cost of the TCP three-way handshake.
  2. Cache handling, increasing theCache-Control(see below for more details);
  3. The request header adds a Host, and HTTP1.0 assumes that each server is bound to a unique IP address, so the URL in the request message does not pass the hostname. However, with the development of virtual hosting technology, there can be multiple homed Web Servers on a physical server, and they share an IP address. HTTP1.1 should support the Host header field in both Request and response messages, and a Request message without the Host header field will report an error (400 Bad Request).
  4. Request header incrementrangeCan be used toBreakpoint continuingly, which supports only requesting a certain part of the resource that can be used forBreakpoint continuingly.
  5. Add request methods :(OPTIONS,PUT, DELETE, TRACE, CONNECT)
  6. Added 24 status codes, such as 100Continue, used before the request bodyRequest headerTest the server before deciding whether to send itRequest body)

** 6.http1.x vs http2.0**

  1. Server push
  2. Multiplexing, where multiple requests are completed on the same TCP connection
  3. Header compression, HTTP2.0 can maintain a dictionary, differential update HTTP header, greatly reduce the traffic generated by header transmission
  • Reference: Differences between HTTP1.0, HTTP1.1, and HTTP2.0

7. Cache-Control

Use to determine strong cache, that is, whether to directly fetch the cached file in the client, without requesting the back end.

Both request headers and response headers can be used.

The cache instructions in a request include no-cache, no-store, max-age, max-stale, Min-fresh, and only- if-cached. The instructions in a response message include: Public, private, no-cache, no-store, no-transform, must-revalidate, proxy-revalidate, max-age.

The meanings of common commands are as follows:

  • no-cache: Does not use the local cache. If there is an ETag in the previous response, then the request will be verified with the server. If the resource is not changed, then the download can be avoided.
  • no-store: Disables the browser from caching data. Each time a user requests the resource, it sends a request to the server and downloads the complete resource each time.
  • public: can be cached by all users, including end users and intermediate proxy servers such as CDN.
  • private: Can only be cached by the browser of the end user and cannot be cached by trunk cache servers such as CDN.
  • max-age: indicates that the client can receive a response whose lifetime is no longer than the specified time (in seconds).

8. https

HTTPS = HTTP + encryption + authentication + integrity protection

Disadvantages of HTTP:

  • The communication uses unencrypted plaintext and the content is vulnerable to theft
  • If the identity of the communicating party is not verified, it is easy to be disguised
  • The integrity of packets cannot be verified and is easily tampered

HTTPS is designed to solve the security problems of the HTTP protocol. HTTPS is not a new protocol at the application layer. It is based on HTTP. The INTERFACES of HTTP and TCP are replaced by SSL and TLS.

HTTP: IP ➜ TCP ➜ HTTP (application layer)

HTTPS: IP ➜ TCP ➜ SSL ➜ HTTP (application layer)

§ encryption

  • Secure Sockets Layer (SSL)
  • Transport Layer Security (TLS)

Symmetric encryption: encryption and decryption using the same key. Common symmetric encryption algorithms: AES, RC4, and 3DES Asymmetric encryption: If the data is encrypted with one key, the other key must be used to decrypt it. Common asymmetric encryption algorithms: RSA, DSA/DSS

Common HASH algorithms are MD5, SHA1, and SHA256

The asymmetric encryption algorithm encrypts the password generated during the handshake, the symmetric encryption algorithm encrypts the transmitted data, and the HASH algorithm verifies the integrity of the data.

Since the password generated by the browser is the key to the whole data encryption, asymmetric encryption algorithm is used to encrypt it during transmission.

The asymmetric encryption algorithm generates a public key and a private key. The public key can only be used to encrypt data, so it can be transmitted at will. The private key of a website is used to decrypt data.

§ CA certificates contain information:

Certification Authority (CA)

  • The public key
  • Web site address
  • The certificate authority
  • Expiration time

§ HTTPS encrypted communication process:

  1. The browser enters a URL to request the site and comes with a set of encryption rules it supports.
  2. The website makes certificate, this should be the website builds a station when already done. Certificates are divided into server certificates and client certificates. We generally refer to the server certificate (Detailed interpretation of the SSL certificate). The production process is as follows:
    1. Make CSR files. During the process of creating a Certificate Secure Request file, the system generates two keys. One is the public key, which is the CSR file, and the other is the private key, which is stored on the server.
    2. The CA certificate. There are two authentication methods for submitting a CSR file to the CA: domain name authentication and enterprise document authentication.
    3. Certificate installation. After receiving the CA certificate, deploy the certificate on the server.
  3. The website selects a set of supported encryption algorithms and hash algorithms from the encryption rules sent by the browser and sends a certificate with a public key to the browser. Of course, the certificate contains information such as the website address, certificate authority, and certificate expiration time.
  4. The browser parses the certificate.
    1. Verify the validity of the certificate. For example, check whether the authority is valid and whether the website address in the certificate is the same as the access address. If the certificate is invalid, a message is displayed indicating that the certificate is untrusted. If the certificate is valid, a small lock is displayed.
    2. If the certificate is valid, or the user accepts an invalid certificate, the browser generates a password (key) of random numbers and encrypts it with the public key provided in the certificate.
    3. The handshake message is calculated using a convention hash, encrypted using the generated random number (the key), and all previously generated messages are sent to the web server.
  5. The web server parses the message. Use the existing private key to decrypt the key, and then use the key to decrypt the handshake message and verify that it matches the one sent by the browser. A handshake message is then encrypted with the key and sent to the browser.
  6. The browser decrypts and computes the HASH of the handshake message. If it matches the HASH sent by the server, the handshake is complete. After that, all communication data is encrypted by the random password generated by the browser and using the symmetric encryption algorithm. Here the browser and the website send each other encrypted handshake messages and verification, the purpose is to ensure that both parties have obtained the same password, and can properly encrypt and decrypt the data, for the subsequent transmission of real data to do a test.

The following figure shows the process of HTTPS encrypted communication:

Design patterns

  • Classification of common design patterns
  • Singleton Pattern
  • Publish subscribe Pattern (also known as Observer Pattern)
  • Mediator Pattern
  • Strategy Pattern
  • Proxy Pattern
  • Iterator Pattern
  • Adapter Pattern
  • Command Pattern
  • Composite Pattern
  • Template Method pattern
  • Flyweight Pattern
  • Model Chain of Responsibility Pattern
  • State Pattern

Git Common Operations

  • Reference: Git Common Operation Guide
The command role
git status
git diff
git add
git commit
git push
git branch
git checkout
git pull/fetch git pull = git fetch + git merge
git merge

§ Git rebase: merge changes from one branch into another.

Objective:

  1. Have submission nodes developed by multiple people on the same branch form a single line, rather than multiple lines
  2. Put your commit at the top of the branch

Usage scenario:

  1. Development branch merges main branch updates;
  2. You cannot use rebase on the primary branch because it would break the history

Git rebase and Git merge do the same thing. They are both designed to incorporate changes in one branch into the other, but in a slightly different way.

  • Git merge sorts the commit records of the two branches in order
  • Git Rebase appends the merged side branch changes directly after the primary branch commit record.

Some other common questions

  • To introduce myself
  • Do you have any hobbies?
  • What are your greatest strengths and weaknesses?
  • Why did you choose this field and position?
  • Do you think you are suitable for this position?
  • What are your career plans?
  • What are your salary expectations?
  • What about front-end development?
  • What’s the plan for the next three to five years?
  • What are the technical difficulties in your project? What’s the problem? How did you solve it?
  • What is the development process in your department
  • Which project do you think did the best work?
  • What are some of the performance optimizations you’ve done at work?
  • What front end is looking at recently the book?
  • How do you learn about front-end development?
  • What is your greatest sense of accomplishment?
  • Why did you leave your last company?
  • How do you feel about working overtime?
  • What do you hope to gain from this job?
  • Do you have any questions to ask after the interview?

clearing

  1. vuex:
    • usage
    • Usage scenarios
    • What problem was solved
    • Vuex interview questions summary
  2. Typescript: 【 OK 】
    • Usage scenarios
    • paradigm
    • Type checking
    • The difference between interface and type aliases
    • Pose used with VUE2 and 3
    • 50 new TypeScript interview questions
  3. Event loop
    • Macro task, micro task
    • Understand JWT, cookie login verification, front and rear deployment modes of corporate projects, and virtualization
  4. git
    • Introduction to core principles
    • Common operations
    • Rebase, merge,
    • Operations related to engineering
    • Git diff file comparison algorithm

reference

  • Introduction of HTTPS
  • Vue source code analysis and understanding of principles
  • “Interview Questions” 20+Vue interview questions