The CSS part

Rem principle

  • The essence of REM layout is proportional scaling, generally based on width, suppose the screen width is divided into 100 parts, each width is 1rem, the width of 1REM is the screen width /100, and then the sub-element sets the rem unit properties.

By changing the font size of the HTML element, you can set the actual size of the child element.

  • Rem layout loading flicker issue
    • The solution is to set the font size of the root element to 750px for the design text. Font-family: arial, sans-serif; font-size: 14px; line-height: 20px; font-size: 14px;
  • Better solution than REM (disadvantages not compatible)
    • Vw (1vw is 1% of the viewport width, 100vw is the viewport width), VH (100vh is the viewport height)

Achieve a three-column layout (fixed width on both sides, adaptive in the middle)

  1. Using absolute causes the parent element to be removed from the document flow, so all child elements need to be removed from the document flow. If the page is complex, you can imagine how difficult it is to develop
  2. When the middle content is higher than the two sides, the height of the two sides will not be higher as the middle content becomes higher
  3. Flexible Box Layout (Flex)
  4. With negative margins and floats, it’s a bit more complicated to implement
  5. Use grid layout
.container {
    display: grid;
    grid-template-columns: 100px auto 200px;
}
Copy the code

BFC (Block-level formatting Context)

  • The principle of landing

These are the BFC’s rendering rules. Including: 1. For the child elements inside the BFC, margins overlap in the vertical direction. 2. BFC is a separate container in a page, and elements outside do not affect elements inside, and vice versa. 3. The BFC area does not overlap the adjacent float box area. (Can be used to remove floating effects). 4. When calculating the height of the BFC, float children are also involved in the calculation.

  • How do I generate a BFC
    • Method 1: Overflow: not visible, can make the properties hidden, auto. 【 Most commonly used 】
    • Method 2: Floating: The property value of float is not None. This means that as soon as the float is set, the current element creates the BFC.
    • Method 3: Positioning: As long as the posiiton value is not static or relative, it can be absolute or fixed, then a BFC is generated.
    • Display inline-block, table-cell, table-caption, flex, inline-flex
  • Landing the application
    • Prevent margin overlap
    • You can include floating elements — clear internal floats (clear floats work when both divs are in the same BFC region)
    • Adaptive two-column layout
    • Prevents elements from being overwritten by floating elements

Flex (often asked in interviews, omitted)

The box model

  1. The CSS box model consists of content, padding, border, and margin.
  2. In the W3C box model, the width/height is set to the width/height of the content. In weird mode, the width/height is set to the content+padding+border width/height.
  3. In the W3C box model, the box size is determined by content, padding, and border, while in weird mode, the box size is determined by width and height.

Js part

Call, apply, bind How to implement the call,apply method

Function.prototype.myBind = function(content) {
    if(typeof this! ='function') {throw Error('not a function')}let _this = this;
    let args = [...arguments].slice(1) 
    let resFn=function(){
        return _this.apply(this instanceof resFn?this:content,args.concat(... arguments)) }return resFn
};
 
 /** * Each function can call the call method to change the this keyword currently executed by the function, and support passing in the argument */
Function.prototype.myCall=function(context=window){
      context.fn = this;// This refers to the function that calls myCall
      let args=[...arguments].slice(1);
      letresult=content.fn(... args)// Destroy this pointer
      delete context.fn;
      return result;
}
/** * The apply function passes in the this pointer and the parameter array */
Function.prototype.myApply = function(context=window) {
    context.fn = this;
    let result;
    if(arguments[1]){ result=context.fn(... arguments[1])}else{
        result=context.fn()
    }
    // Destroy this pointer
    delete context.fn;
    return result;
}
Copy the code

The function is currified

Js inheritance, constructor, prototype chain, constructor, prototype chain combinatorial inheritance, parasitic combinatorial inheritance, Object. Create polyfill;

Array to heavy

[...new Set(arr)]
Copy the code
var arr = [1.2.1.2.3.5.4.5.3.4.4.4.4],
    init=[]
var result = arr.sort().reduce((init, current) = >{
    console.log(init,current)
    if(init.length===0 || init[init.length-1]! ==current){ init.push(current); }returninit; } []);console.log(result);/ / 1, 2, 3, 4, 5
Copy the code

If the throttle

var deBounce=function(fn,wait=300){
    let timer
    return function(){
      if(timer){
          clearTimeOut(timer)
      }
      timer=setTimeOut(() = >{
          fn.apply(this.arguments)
      },wait)
    } 
}
 var throttle = function (fn, wait = 300) {
        let prev = +new Date(a);return function () {
          const args = argument,
          now = +new Date(a);if (now > prev + wait) {
            prev = now;
            fn.apply(this, args)
          }
        }
     }
Copy the code

Implementing the Promise idea

//0 pending,1 resolve,2 reject 

function Promise(fn) {...
	this._state = 0 // Status flag
	doResolve(fn, this)}function doResolve(fn, self) {
	var done = false // Ensure that only one listener is executed
	try {
		fn(function(value) {
			if (done) return
			done = true
			resolve(self, value)
		}, function(reason) {
			if (done) return;
			done = true
			reject(self, value)
		})
	} catch (err) {
		if (done) return
		done = true
		reject(self, err)
	}
}

function resolve(self, newValue) {
	try {
		self._state = 1; . }catch (err) {
		reject(self, err)
	}
}

function reject(self, newValue) {
	self._state = 2; .if(! self._handled) {Promise._unhandledRejectionFn(self._value); }}Copy the code

Implementing deep copy

funtion deepCopy(obj){
    let result;
   if(typeofObj=='object') {// Complex data types
       result=obj.constructor==Array? [] : {}for (let i in obj){
           result[i]=typeof obj[i]=='object'? deepCopy(obj[i]):obj[i] } }else{
       // Simple data types
       result=obj
   }
   return result
}
Copy the code

The re implements the thousands separator

function commafy(num) {
        return num && num
            .toString()
            .replace(/(\d)(? =(\d{3})+\.) /g.function($0, $1) {
                return $1 + ",";
            });
    }
 console.log(commafy(1312567.903000))
Copy the code

Js event loop

Javascript is a single-threaded language, and tasks are designed into two types: synchronous and asynchronous tasks, which go to different execution “places”, synchronous into the main thread, and asynchronous into the Event Table and register functions. When the specified Event completes, the Event Table moves this function to the Event Queue. All tasks in the main thread are empty, and the Event Queue reads the corresponding function to enter the main thread. This process is repeated over and over again, known as an Event Loop. If a macro task is encountered, the macro task will be executed first, the macro task will be put into the Event queue, and then the micro task will be executed, and the micro task will be put into the eventQueue. However, the two queues are not the same. When you go out, you take the callback from the microtask first, and then you take the callback from the macro task queue. Macro tasks usually include: script, setTimeout, setInterval. Microtasks: Promise, process.nexttick

The event flow mechanism, the difference between event delegates event.targe and Event.currenttarget

  • Event bubbling and event capture
  • The event flow is divided into bubble and capture, in the order of capture and then bubble.
  • Event bubbling: Triggering events for child elements are passed to the parent until the root stops. During this process, relevant events can be captured at each node. Bubbling can be stopped using the stopPropagation method.
  • Event capture: As opposed to “event bubbling,” execution starts at the root node and continues through child nodes to the target node.
  • Event capture phase

AddEventListener gives a third argument that supports both bubbling and capturing: false by default, event bubbling; When set to true, event capture.

  • Event delegation Event delegation refers to binding the event to the parent element of the target element, using the bubble mechanism to trigger the event

    • You can reduce event registration and save a lot of memory by applying events to dynamically added child elements
  • Event. target returns the element that triggered the event

  • Event.currenttarget returns the element to which the event is bound

The process of new and implementing new

1 / / method
function create(){
   //1. Create an empty object
   let obj={}
   //2. Get constructor
   let Con=[].shift.call(arguments)
   //3. Set the empty object prototype
   obj._proto_=Con.prototype
   //4. Bind this and execute the constructor to add attributes and methods to the new object
   let result=Con.apply(obj,arguments)
   //5. Make sure the return value is an object
   return result instanceof Object? result:obj }2 / / method
// We can see that when a function is new,
// will return a func and inside that func will return an Object,
// This object contains attributes of the parent func class and a hidden __proto__
function New(f) {
    // return a func
    return function () {
        var o = {"__proto__": f.prototype};
        f.apply(o, arguments);// Inherits the attributes of the parent class

        return o; Return an Object}}Copy the code

Encapsulation ajax

/* Encapsulate ajax functions * @param {string}opt.type HTTP connection mode, Url URL for sending requests * @param {Boolean} Opt. Async Specifies whether the request is asynchronous. True indicates that the request is asynchronous. False is the parameter sent by synchronous * @param {object}opt.data in the format of object type * @param {function}opt.success Ajax sends and receives successfully called callback function */
function myAjax(opt){
     opt = opt || {};
     opt.method = opt.method.toUpperCase() || 'POST';
     opt.url = opt.url || ' ';
     opt.async = opt.async || true;
     opt.data = opt.data || null;
     opt.success = opt.success || function () {}
     let xmlHttp = null;
     if (XMLHttpRequest) {
        xmlHttp = new XMLHttpRequest();
     }else{
         xmlHttp =new ActiveXObject('Microsoft.XMLHTTP')}let params;
    for (var key in opt.data){
        params.push(key + '=' + opt.data[key]);
    }
    let postData = params.join('&');
    if (opt.method.toUpperCase() === 'POST') {
        xmlHttp.open(opt.method, opt.url, opt.async);
        xmlHttp.setRequestHeader('Content-Type'.'application/x-www-form-urlencoded; charset=utf-8');
        xmlHttp.send(postData);
    }else if (opt.method.toUpperCase() === 'GET') {
        xmlHttp.open(opt.method, opt.url + '? ' + postData, opt.async);
        xmlHttp.send(null);
    } 
     xmlHttp.onreadystatechange= function () {
            if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
                opt.success(xmlHttp.responseText);// Opt. Success (json.parse (xmlhttp.responseText))}}; }Copy the code

Url with parameters

var url = "http://www.taobao.com/index.php?key0=0&key1=1&key2=2";
function parseQueryString(url){
    var str = url.split("?") [1]./ / by? I get an array. I take? The following parameters
        items = str.split("&");    // Split into arrays
    var arr,name,value;

    for(var i=0; i<items.length; i++){
        arr = items[i].split("=");    //["key0", "0"]
        name = arr[0];
        value = arr[1];
        this[name] = value; }}var obj = new parseQueryString(url);
alert(obj.key2)
Copy the code

HTTP part

The HTTP protocol

HTTP protocol (Hypertext Transfer Protocol)

  • 1.0 Protocol Defects:
  • Unable to reuse the link, disconnect upon completion, restart slowly and TCP 3 – way handshake
  • Head of line blocking: Blocking is blocking, causing requests to interact with each other

1.1 improvements:

  • Long connection (default keep-alive), multiplexing
  • The host field specifies the corresponding virtual site
  • New features:
    • Breakpoint continuingly
    • The identity authentication
    • State management
    • Cache cache
      • Cache-Control
      • Expires
      • Last-Modified
      • Etag
  • 2.0:
  • multiplexing
  • Binary framing layer: between the application layer and the transport layer
  • The first compression
  • Server push

HTTP Request message Request

  1. Request line, header, blank line and request data are composed of four parts.
  2. A request line that specifies the type of request, the resource to access, and the HTTP version to use.
  3. The request header, the part immediately after the request line (the first line), is used to specify additional information to be used by the server
  4. Blank line, the blank line after the request header is required
  5. Request data, also known as the body, can be added to any other data.

HTTP Response message Response

The HTTP response also consists of four parts: the status line, the message header, the blank line, and the response body.

  1. The status line consists of the HTTP protocol version number, status code, and status message.
  2. A message header that specifies some additional information to be used by the client
  3. Part 3: Blank lines. Blank lines after the message header are required
  4. Part four: Response body: the text message returned by the server to the client.

Enter the URL in the browser’s address bar and press Enter to go through the following process:

  1. The browser requests the DNS server to resolve the IP address corresponding to the domain name in the URL.
  2. Establish a TCP connection (three-way handshake).
  3. The browser sends an HTTP request to read a file (the file following the domain name in the URL). The request packet is sent to the server as the third packet of the TCP three-way handshake.
  4. The server responds to the browser request and sends the corresponding HTML text to the browser;
  5. Release TCP connection (wave four times);
  6. The browser renders the HTML text and displays the content;

Three-way handshake

SYN (Synchronization sequence number) ACK (acknowledgment character)

  1. First handshake: The Client sets the SYN flag bit to 1, randomly generates a value seq=J, and sends the packet to the Server. The Client enters the SYN_SENT state and waits for confirmation from the Server.
  2. Second handshake: When the Server receives the packet, the flag bit SYN=1 knows that the Client requests to establish a connection. The Server sets the flag bit SYN and ACK to 1, ACK =J+1, randomly generates a value seq=K, and sends the packet to the Client to confirm the connection request. The Server enters the SYN_RCVD state.
  3. Third handshake: After receiving the confirmation, the Client checks whether the ACK is J+1 and ack is 1. If yes, the Client sets the flag ACK bit to 1, ack=K+1, and sends the packet to the Server. The Server checks whether the ACK is K+1 and ACK is 1. The Client and Server enter the ESTABLISHED state and complete the three-way handshake. Data can be transmitted between the Client and Server.

Four times to wave

  1. First wave: The Client sends a FIN to stop data transmission from the Client to the Server, and the Client enters the FIN_WAIT_1 state.
  2. Second wave: After receiving a FIN, the Server sends an ACK to the Client. The ACK sequence number is +1 (the same as that for SYN, one FIN occupies one sequence number). The Server enters CLOSE_WAIT state.
  3. Third wave: The Server sends a FIN to disable data transfer from the Server to the Client, and the Server enters the LAST_ACK state.
  4. Fourth wave: After receiving the FIN, the Client enters the TIME_WAIT state and sends an ACK to the Server to confirm that the FIN number is +1. The Server enters the CLOSED state and waves four times.

Why is it three handshakes to establish a connection, but four waves to close it?

This is because in LISTEN state, the server receives a SYN packet for establishing a connection and sends the ACK and SYN packets to the client. And close the connection, when I received the other side of the FIN message just said to each other can no longer send data but also receives the data, the board may not all data are sent to each other, so their can immediately close, also can send some data to each other, then send the FIN message now agreed to close the connection to the other side, therefore, Your ACK and FIN are usually sent separately.

The process of web page generation can be roughly divided into five steps:

  1. The HTML code is converted to the DOM
  2. The CSS code is converted to CSSOM
  3. Combine DOM and CSSOM to generate a render tree
  4. Generate the layout layout, that is, all the nodes of the render tree for the plane composition
  5. Paint the layout on the screen (can be extended to reduce backflow and redraw of browser rendering)

How HTTPS works

Asymmetric encryption and symmetric encryption are combined, asymmetric encryption algorithm is used to transfer the key for symmetric encryption algorithm, and then symmetric encryption algorithm is used for information transfer. It’s safe and efficient

Browser cache

When the browser accesses an already accessed resource again, it does this:

  1. See if the strong cache is hit, and if so, use the cache directly.
  2. If the strong cache is not hit, a request is sent to the server to check for a hit to the negotiation cache.
  3. If the negotiated cache is hit, the server returns 304 telling the browser to use the local cache.
  4. Otherwise, return the latest resource.
  5. Strong cache
    • Expires
    • Cache-control
  6. Negotiate the cache
    • Last-Modified/If-Modified-Since
    • Etag/If-None-Match

vue&react

Virtual DOM

In fact, VNode is an abstract description of the real DOM. Its core definition is nothing more than a few key attributes, tag name, data, child nodes, key values, etc. Other attributes are used to extend the flexibility of VNode and implement some special features. Since VNode is only used for rendering that maps to the real DOM and does not need to include methods to manipulate the DOM, it is very lightweight and simple. In addition to the definition of the Virtual DOM’s data structure, mapping to the real DOM actually involves VNode’s create (simulating the DOM tree with JS objects), diff (comparing the differences between two Virtual DOM trees), and patch (applying the differences to the real DOM tree).

The diff algorithm

  • When the DIff algorithm compares old and new nodes, it only compares them at the same level, not across levels
  • When the data changes, a new VNode will be generated, and then the new VNode will be compared with the oldNode, and the differences will be directly modified in the real DOM. The old and new nodes will be compared, and the real DOM will be patched while the comparison is made
  • Node keys can be set to make efficient use of dom (preferably not index key)
  • The virtual DOM Diff algorithm is mainly optimized for the following three scenarios:
  1. tree diff

For hierarchical comparison of trees, only nodes of the same level are compared between two trees. (Because DOM node movement across hierarchies is negligible.) If the parent node no longer exists, the node and its children are removed completely and not used for further comparison. Note: React does not recommend cross-hierarchy DOM node operations, which may affect React performance. When developing components, maintaining a stable DOM structure can help improve performance. For example, you can hide or show nodes through CSS without actually removing or adding DOM nodes.

  1. component diff

If the components are of the same type, continue to compare the virtual DOM Tree (Tree Diff) according to the original policy. For components of the same type, it is possible that the Virtual DOM does not change at all. Knowing this for sure can save a lot of diff time. React therefore allows the user to determine if the component needs to diff by shouldComponentUpdate(). If not, simply replace all child nodes under the entire component.

  1. element diff

Compare nodes at the same level. React advises: Add a unique key to distinguish between different keys. Although it is only a small change, the performance has undergone a dramatic change! A B C D –> B A D C = A, create and insert B into new set, delete old set A; Similarly, create and insert A, D, and C, and delete B, C, and D. After the key is added, users B and D do not perform any operation, and users A and C move the key. Suggestion: During the development process, try to minimize operations such as moving the last node to the head of the list. If the number of nodes is too large or update operations are too frequent, the rendering performance of React will be affected to some extent.

  1. conclusion
  • React converts O(N3) complexity problems into O(n) complexity problems by implementing a bold diff strategy;
  • React optimizes the Tree Diff algorithm by adopting a hierarchical differentiation strategy.
  • React optimizes the Component diff algorithm by generating similar tree structures from the same class and different tree structures from different classes.
  • React optimizes the algorithm on Element Diff by setting a unique key policy.
  • It is recommended that when developing components, maintaining a stable DOM structure will help improve performance;
  • It is recommended to minimize operations like moving the last node to the head of the list during development. When the number of nodes is too large or update operations are too frequent, React rendering performance will be affected to some extent.

The responsive principle of VUE

  • Object.defineProperty(obj, prop, descriptor)
  • Obj is the object on which attributes are to be defined; Prop is the name of the property to be defined or modified; Descriptor is the property descriptor to be defined or modified.

The core descriptor is descriptor, which has a bunch of optional key values, and you can refer to its documentation for details. Here we care most about get and set. Get is a getter method for a property that fires when it is accessed; Set is a setter method for a property that is triggered when we make changes to that property. Once an object has a getter and setter, we can simply call this object a reactive object – object recursive call – solution to array variation methods: proxy prototype/instance methods

  • observe
  • The observe method adds an Observer to a non-VNode object. If an Observer has been added, return it. Otherwise, instantiate an Observer if certain conditions are met.
  • Observe’s function is to monitor data changes.
  • An Observer is a class that adds getters and setters to properties of an object for dependency collection and distribution of updates:
  • Rely on collecting and distributing updates
  • The purpose of collecting dependencies is to know which subscribers should be notified to do the logical processing when these reactive data changes and trigger their setters. We call this process dispatching updates. In fact, Watcher and Dep are a very classic implementation of the observer design pattern
  • Sending out updates is when the data changes, triggers setter logic, and triggers the update process for all observers subscribed to in the dependency process, namely watcher, which is further optimized to take advantage of queues. Execute all watcher runs after nextTick, and finally execute their callback functions
  • Vue Compile the process is mainly divided into the following steps

Parse (generate AST)=> optimize(static node)=> Generate (render function)

// Parse the template string to generate the AST
const ast = parse(template.trim(), options)
// Optimize the syntax tree
optimize(ast, options)
// Generate code
const code = generate(ast, options)
Copy the code

Vue compute and Watch

  • Computed is a property that relies on other properties to compute values, and computed values are cached and returned only when computed values change.
  • Watch listens for a change in the value and executes a callback, in which logical operations can be performed.
  • So generally, computed can be used when you need to rely on other attributes to get values dynamically, and Watch can be used when you need to do some complex business logic to listen for changes in values.

Understanding of VUEX, one-way data flow

vuex

  • State: indicates the state center
  • 2. mutations
  • Actions: Changes status asynchronously
  • Getters: Gets the status
  • Modules: Split state into modules for easy management
    • Mutations and action

Two implementation principles of front-end routing

  1. Hash pattern
  • The Window object provides an onHashChange event to listen for changes in the hash value, which is triggered whenever the hash value in the URL changes.
  1. The History mode
  • Popstate listens for historical stack information changes and rerenders as it changes
  • Add functionality using the pushState method
  • Replace functionality with replaceState

The front security

XSS and CSRF

  • XSS: Cross-site scripting attack, is a website application security vulnerability attack, is a kind of code injection. Common way is to inject malicious code into legitimate code to hide, and then induce malicious code, so as to carry out a variety of illegal activities.

Prevention:

  • Using the XSS Filter
    1. Input filtering validates user-submitted data, accepts only content submitted within a specified length and in the format we expect, and blocks or ignores any other data.
    2. Output escape: When a string needs to be output to a Web page, and it is not sure whether the string contains XSS special characters, to ensure the integrity and correctness of the output content, the OUTPUT OF HTML attributes can be processed by HTMLEncode, output to<script>, can be JS encoding.
  • Use the HttpOnly cookies

Mark important cookies as HttpOnly, so that when the browser makes a request to the Web server, the cookie field is attached, but the cookie cannot be accessed in the JS script. This avoids XSS attacks that use JavaScript document.cookie to get cookies.

  • CSRF: Cross-site request forgery, also known as XSRF, is an attack that tricks a user into performing unintended actions on a currently logged Web application. In contrast to XSS, XSS exploits the user’s trust in a given web site, and CSRF exploits the site’s trust in the user’s Web browser.
  1. Prevention: User restrictions – captcha mechanism
  • Method: Add a captcha to identify whether the user initiated the request, because a strong captcha machine can not recognize, so dangerous sites can not forge a complete request.
  • Advantages: Simple and crude, low cost, reliable, can prevent 99.99% of attackers.
  • Cons: not user friendly.
  1. Request source restriction – Validate the HTTP Referer field
  • Method: In the HTTP request header there is a field called Referer, which records the source address of the request. What the server needs to do is verify that the source address is legitimate and reject the response if it comes from some untrusted site.
  • Advantages: zero cost, simple and easy to implement.
  • Cons: Because this method is heavily browser-dependent, security depends on the browser.
  • Additional authentication mechanism — use of tokens
  1. Method: Use token instead of verification code. Since a hacker cannot access and see the contents of a cookie, he cannot forge a complete request. The basic idea is as follows:
  2. The server randomly generates tokens (such as cookies hash), stores them in the session, places them in cookies or delivers them to the front-end in ajax form.
    • When the front-end sends a request, it parses the token in the cookie and places it in the request URL or in the request header.

    • The server validates the token and is protected against CSRF because the hacker cannot obtain or forge the token