Github version stamp, ask star,follow

preface

The content of the article may not be comprehensive, but the amount is very large, need to read slowly. From all over the place, I spent a long time to organize, I hope to help you. However, it is hard to avoid typing mistakes or understanding mistakes. If you find any, please let me know by email at [email protected]. I will timely modify it.

The front-end directory

  1. The HTML related
  2. CSS related
  3. JAVASCRIPT related
  4. DOM related
  5. HTTP related
  6. VUE related
  7. Algorithm related
  8. Network Security Related
  9. Webpack related
  10. other

The Html related

1. HTML semantics

Meaning: Based on the structure of the content (semantic content), choosing the right tags (semantic code) makes it easier for developers to read and write more elegant code while allowing browsers and machines to parse well. Note:

1. Use non-semantic div and span tags as little as possible;

2. When the semantics are not obvious, when both div and P can be used, try to use P, because p has up and down spacing by default, which is beneficial to compatible with special terminals;

3. Instead of using pure style labels such as B, FONT, u, etc., use CSS Settings instead.

4. Text that needs to be emphasized can be included in the strong or em tag (the browser’s default styles can be specified with CSS, but do not use them). By default, strong is bold (do not use b) and em is italic (do not use I).

If you want to use a table with a caption, “Thead” at the head, “tbody” at the head, and “tfoot” at the end. The header should be separated from the normal cell. The header should be th and the cell should be TD.

6. The field should be wrapped in a fieldSet tag and the legend tag should explain the purpose of the form.

7. The description for each input label needs to use the label label, and the description is associated with the corresponding input by setting the ID attribute for the input and for= SOMeld in the lable label.

The new label:

2 Meta Viewport related

       H5 standard declaration, using HTML5 docType, is case insensitive<head lang="En">The standard way to write the lang attribute<meta charset='utf-8'>Specifies the character encoding used by the document<meta http-equiv="X" - UA - Compatible content="IE=edge,chrome=1 /">Preferentially use the latest version of IE and Chrome<meta name="Description" content=The value contains a maximum of 150 characters>Page description<meta name="Keywords" content="/">Page keywords<meta name="The author" content="The name, email@gmail.com"/ >Web authors<meta name="Robots" content="The index, follow" />Search engine crawl<meta name="Viewport" content="The initial scale=1, maximum-scale=3, minimum-scale=1, user-scalable=No">Add a Viewport for the mobile device<meta name="Apple -- mobile web app - title" content="Title">IOS devices begin<meta name="Apple -- mobile web app - capable" content="Yes" />After adding the title to the home screen (added in iOS 6) whether to enable WebApp full screen mode, remove Apple's default toolbar and menu bar<meta name=Apple - itunes - app" content="App - id=myAppStoreID, affiliate-data=myAffiliateData, app-argument=MyURL">Add Smart App Banner (iOS 6+ Safari)<meta name="Apple -- mobile web app - the status bar - style" content="Black" />
<meta name="The format - detection" content="Telphone=no, email=No "/>Set the apple toolbar color<meta name="The renderer" content="Its">Enable webKit for 360 browser<meta http-equiv="X" - UA - Compatible content="IE=The edge">Avoid IE using compatibility mode<meta http-equiv="Cache-control" content="No - siteapp" />Don't let Baidu transcode<meta name="HandheldFriendly" content="True">Optimized for handheld devices, mainly for older browsers that don't recognize viewports, such as blackberry<meta name="MobileOptimized" content="320">Microsoft's old browser<meta name="Screen -" orientation" content="Portrait">Uc Mandatory portrait<meta name="X5 -" orientation" content="Portrait">QQ mandatory portrait<meta name="Full screen" content="Yes">UC mandatory full screen<meta name="X5 - fullscreen" content="True">QQ mandatory full screen<meta name="Browsermode" content="Application">UC Application Mode<meta name="X5 - page - mode. content="App">QQ Application Mode<meta name="Msapplication - tap - highlight" content="No">Windows Phone click no Highlight Settings page is not cached<meta http-equiv="Pragma" content="No - cache">
<meta http-equiv="Cache-control" content="No - cache">
<meta http-equiv="Expires" content="0">
Copy the code
3 canvas relevant
Context must be obtained before use, which is not supported currently3D common API:1.FillRect (x,y,width,height) Solid rectangle2.StrokeRect (x,y,width,height) hollow rectangle3.fillText("Hello world".200.200); Solid words4.strokeText("Hello world".200.300) hollow text all kinds of things!!Copy the code
The new label is compatible with earlier versions
  1. Previous versions of IE9 created a new HTML5 tag with createElement
  2. The introduction of html5shiv. Js

CSS related

1. The box model

1. The IE box model counts the border, padding and itself (not counting margin), the standard only counts the size of its own window CSS setting method is as follows

/* Standard model */
box-sizing:content-box;
 / * * / IE model
box-sizing:border-box;
Copy the code

2. Margin, border, padding, content Several ways to obtain width and height

  • Dom.style.width /height this method can only retrieve the width and height set by the inline style of the DOM element. That is, if the style of the node is set in the style tag or in an external CSS file, this method cannot retrieve the width and height of the DOM element.
  • Dom. CurrentStyle. Width/height is obtained after the page rendering this way, the result of the style to say either way, you can get. However, this method is only supported by Internet Explorer.
  • Window.getcomputedstyle (dom).width/height: window.getComputedStyle(dom).width/height: window.getComputedStyle
  • Dom. GetBoundingClientRect (). The width/height is this way according to the elements in the Windows of the absolute position to obtain wide high
  • The dom. The offsetWidth/offsetHeight that have nothing to say, the most commonly used, is also compatible with the best.

4. Expand the ways to obtain width and height

  • To obtain the height and width of the screen (screen resolution) : window. The screen. The height/width
  • Access to the working area of the screen height and width (remove the status bar) : window. Screen. AvailHeight/availWidth
  • Web page full height and Width: the document body. ScrollHeight/Width
  • Scroll bar roll up to the height and the width of the roll to the right: the document. The body. The scrollTop/scrollLeft
  • Web page visible region of the height and width (without border) : document. Body. ClientHeight/clientWidth
  • Web page visible region of the height and width (line) : document. Body. OffsetHeight/offsetWidth

5. Margin Overlap solution (BFC) PRINCIPLE of BFC

  • The inner boxes will be placed vertically, one after the other, to the left of each element’s margin box, touching the left of the containing block’s border box (for formatting from the right, otherwise the opposite).
  • The vertical distance of box is determined by margin. Margins of two adjacent boxes belonging to the same BFC will overlap
  • The region of the BFC does not overlap the box of the floating region
  • The BFC is a separate container on a page. Elements on the outside do not affect elements in the BFC, and in turn, elements on the inside do not affect those on the outside
  • When calculating the height of the BFC, the floating element also participates in the calculation of creating the BFC
  • Float property not None (out of the document stream)
  • Position is absolute or fixed
  • The display for the inline – block, table – cell, table – caption, flex, inine – flex
  • The overflow is not visible
  • The root element demo
<section class="top">
	<h1>on</h1>The margin - bottom: 30 px;</section>
<! Add a parent element to the following block and create BFC on the parent element -->
<div style="overflow:hidden">
	<section class="bottom">
	<h1>Under the</h1>The margin - top: 50 px;</section>
</div>
Copy the code
What is the difference between CSS reset and normalize. CSS
  • In both cases, styles are reset to keep the browser style consistent
  • The former adds styles to almost all tags, while the latter keeps many browser styles as consistent as possible
  • The latter fixes common desktop and mobile browser bugs: including display Settings for HTML5 elements, font-size problems with preformatted text, SVG overflow in IE9, and many form-related bugs in browsers and operating systems.
  • The former contains large chains of inheritance
  • The latter is modular and more well-documented than the former
The middle way

horizontally

forinlineInline blocks,inline-block, inline tableinline-table.inline-flexElements andimg.span.buttonElements such as.text_div{
	text-align:center;
}
Copy the code
Margin :0 auto; text_div{margin:0 auto; // Set the parent width;Copy the code
By setting the parent elementfloatThen set the parent elementposition:relativeleft: 50%, child element Settingsposition:relativeleft: - 50% to achieve horizontal center..wrap{
    float:left;
    position:relative;
    left:50%;
    clear:both;
}
.wrap-center{
    left: -50%;
}
Copy the code

Vertical center

Single line inlining (inline-By setting the height of the inline element (height) and the row height (line-height), so that the element is vertically centered..text_div{
    height: 120px;
    line-height: 120px;
}
Copy the code
Using table layout.father {
    display: table;
}
.children {
    display: table-cell;
    vertical-align: middle;
     text-align: center; 
}
Copy the code
{display: flex; display: flex; flex-direction: column; // Array-text: center-content: center; }Copy the code
Absolute layout with known height.parent {
  position: relative;
}
.child {
  position: absolute;
  top: 50%;
  height: 100px;
  margin-top: -50px; } unknown height.parent {
    position: relative;
}
.child {
    position: absolute;
    top: 50%;
    transform: translateY(50%); }Copy the code

Vertical horizontal center according to the top combination

flexway.parent {
    display: flex;
    justify-content: center;
    align-items: center;
}
gridway.parent {
  height: 140px;
  display: grid;
}
.child { 
  margin: auto;
}
Copy the code
The CSS priority is determined
  • Each selector has a value, and the larger the weight, the higher the priority
  • Inherited styles take precedence over self-specified styles
  • ! Important with the highest priority cannot be changed
  • At the same weight, styles near the elements have higher priority in the order inline style sheet (inside the tag) > Internal style sheet (in the current file) > external style sheet (in the external file)
See box model for BFC content
How to Clear a Float

Unclear floating height collapse: Floating element parent element height adaptive (if the parent element does not write height, after the child element writes float, the parent element height collapse will occur)

  • Add an empty div below the floating element and write a CSS style to the element: {clear:both; height:0; overflow:hidden; }
  • Sets the height of the floating element parent
  • Parent floats at the same time (floats need to be added to parent sibling elements)
  • The parent is set to inline-block and its margin: 0 auto center mode is invalid
  • Clear float method by adding overflow:hidden to parent
  • Universal clearing method after pseudo-class clearing float (now the mainstream method, recommended to use)
.float_div:after{
	content:".";
	clear:both;
	display:block;
	height:0;
	overflow:hidden;
	visibility:hidden;
}
.float_div{
	zoom:1
} 
Copy the code
Adaptive layout

Ideas:

  1. Left float or absolute position, then right margin brace
  2. Use div to contain, and then form BFC by negative margin
  3. Using flex
Draw a triangle
#item {
	width: 0;
	height: 0;
	border-left: 50px solid transparent;
	border-right: 50px solid transparent;
	border-top: 50px solid transparent;
	border-bottom: 50px solid blue;
	background: white;
}
Copy the code
Link@import Imports CSS
  1. Link is an XHTML tag that, in addition to loading CSS, can define other transactions such as RSS; @import belongs to the CSS category and can only load CSS.
  2. When the link references the CSS, it is loaded at the same time as the page is loaded. @import requires the page to load after the page is fully loaded.
  3. Link has no compatibility problem. @import was introduced in CSS2.1 and is not supported by earlier browsers.
  4. Link supports using Javascript to control the DOM to change styles; @import is not supported.
animation

Aspect ratio scheme
  1. Use padding in combination with calC implementation
  2. Set the percentage for one item and the aspect-ratio for the other (with plug-in implementation)
The display related
  1. Block: container types such as div
  2. Inline: inline types such as img span
  3. Table series: Changes style to table type
  4. Flex: Focus, very powerful
  5. The grid: same as above
  6. Inline-block: Width can be set, with a slight gap between the two
  7. Inherit: inherits from its parent

JavaScript related

1 [“1”, “2”, “3”].map(parseInt)
First, map takes two arguments, a callback function and a callback functionthisWhere the callback function takes three arguments: currentValue, index, arrary; In this case, map only passes the callback function --parseInt. Second,parseIntOnly two string parameters are accepted, radix(radix) and index (radix)parseInt('1'.0);
parseInt('2'.1);
parseInt('3'.2);

parseInt(String, radix) String is required. The string to parse. Radix is optional. Represents the cardinality of the number to be parsed. This value is between2 ~ 36In between. If this parameter is omitted or its value is0, the number will be10Based on. If it starts with"0X "or"0X "will begin with16As the base.Copy the code
2 [[3, 2, 1]. The reduce () Math. The pow, [] the reduce () Math. The pow]
Arr. reduce(callback[, initialValue]) reduce takes two parameters, a callback and an initialValue. The callback function takes four arguments: previousValue, currentValue, currentIndex, If the array is empty and no initialValue was provided,TypeErrorL: m = m = m = m = m = m = m = m = m = m = m = m = m So this first expression is the same thing asMath.pow(3.2) = >9; Math.pow(9.1) = >9
Copy the code
3
var ary = [0.1.2];
ary[10] = 10;
ary.filter(function(x) { return x === undefined; }); We see that when we iterate through the array, we first check whether the index is a property of the array, so let's test that.0 inary; = >true
3 inary; = >false
10 inary; = >trueThat is to say from3 - 9All uninitialized bugs! These indexes do not exist in the array. These pits are skipped when array functions are called.Copy the code
4 [typeof null, null instanceof Object]
typeofReturns a string representing the type. The instanceof operator is used to detectconstructorType result Undefined "Undefined" Null "object" Boolean "Boolean" Number "Number" String "string" Symbol "symbol" Host object Implementation-dependent Function "function" Object "object"Copy the code
5 js data types

1.number;

2.string;

3.boolean;

4.undefined;

5.null;

6. Symbol (ES6) generates a globally unique value.

7.Object. (include Object, Array, Function)

6 promise usage
definevar promise = new Promise(function(resolve, reject) {
  // ... some code
  if (/* Asynchronous operation succeeded */){
    resolve(value);
  } else{ reject(error); }}); Using a promise. Then (function(value) {
  // success
}, function(error) {
  // failure
});
// Equivalent to:
promise.then(function(){
  //success
}).catch(function(){
  //failure
})
Copy the code
7 es6 promise ajax
defineconst myHttpClient = url= > {
  return new Promise((resolve, reject) = > {
    let client = new XMLHttpRequest();
    client.open("GET", url);
    client.onreadystatechange = handler;
    client.responseType = "json";
    client.setRequestHeader("Accept"."application/json");
    client.send();
    function handler() {
      if (this.readyState ! = =4) {
        return;
      }
      if (this.status === 200) {
        resolve(this.response);
      } else {
        reject(new Error(this.statusText)); }}}); }; The use of myHttpClient ('https://www.baidu.com').then(res= > {
  console.log(res);
}).catch(error= > {
  console.log(error);
});
Copy the code
8 closure
function foo(x) {
    var tmp = 3;
    return function (y) { alert(x + y + (++tmp)); }}var bar = foo(2); // Bar is now a closure
bar(10); As a result,16Es6 usually uselet constBlock-level scoping substitution, closure disadvantages, ie can cause memory leaks, strictly speaking, is a shortcoming of IE is not the problem of closuresCopy the code
What is an immediate execution function? What is the purpose of using immediate execution functions?
There are two common ways1.(function(){... }) () (function(x){
	  console.log(x); }) (12345)
2.(function(){... } ()) (function(x){
	  console.log(x); } (12345If needed, pass it in as a variable such as (function(window){... } (window))Copy the code
10 async/await the grammar
What it does: Example of a new way to asynchronous code promiseconst makeRequest = (a)= > {
  return getJSON()
    .then(data= > {
      if (data.needsAnotherRequest) {
        return makeAnotherRequest(data)
          .then(moreData= > {
            console.log(moreData)
            return moreData
          })
      } else {
        console.log(data)
        return data
      }
    })
}
async/awaitThe sampleconst makeRequest = async() = > {const data = await getJSON()
  if (data.needsAnotherRequest) {
    const moreData = await makeAnotherRequest(data);
    console.log(moreData)
    return moreData
  } else {
    console.log(data)
    returnThe data}} function is preceded by an ayNC keyword.awaitKeywords can only be used in functions defined by ayNC.asyncThe function implicitly returns a promise whose reosolve value is the functionreturnThe value of the. (In the example, the reosolve value is a string"done")
Copy the code
11 Depth copy
let a = {
  aa: 1.bb: 2.cc: 3.dd: {
    ee: 5,},ff: {
    gg: 6,}};let d = JSON.parse(JSON.stringify(a));// Deep copy contains child objects
letc = {... a};// Copy a layer with no child objects
let b = a;/ / shallow copy
b.bb = 22;
c.cc = 33;
c.dd.ee = 55;
d.ff.gg = 66;
console.log(a);
console.log(b);
console.log(c);
console.log(d);
Copy the code
12 Deduplicate arrays
Train of thought1: defines a new array, and stores the first element of the original array, and then compares the elements of the new array with the elements of the new array, if different, stored in the new array idea2: sort the original array, compare it with the adjacent array, and save the new array if different. Train of thought3: Takes advantage of the existence of an object property, and saves it to a new array if it does not exist. Train of thought4(Most common) : Use the ES6 setlet arr= [1.2.3.3.5.7.2.6.8];
console.log([...new Set(arr)]);
Copy the code
13 Regular trim() function
function myTrim(str) {
  let reg = /^\s+|\s+$/g;
  return str.replace(reg, "");
}
console.log(myTrim(' asdf '));
Copy the code
14 JS prototype
1.Every object has a __proto__ property, but only function objects have a prototype property2.My rough understanding of it is similar to python's class methods and static method instance methodsCopy the code
15 es6 class
Object oriented, class in JavaCopy the code
How does JS implement inheritance
1.Using stereotype inheritance (inheriting both the parent template and the parent stereotype object. The advantage is inherited from the template of the parent class, and inherited from the prototype object of the parent class, the disadvantage is that the parent class instance pass parameters, not the subclass instantiation pass parameters, does not conform to the general language writing method)2.Use the call method (inherited from the parent template, not from the parent prototype object). The advantage is that it is convenient for subclass instances to pass parameters, the disadvantage is that it does not inherit the prototype object of the parent class.Copy the code
17. Write jquery plug-ins by hand
(function ($) {
	$.fn.myPlugins = function (options) {
	  // Parameter assignment
	  options = $.extend(defaults, options);// Object merge
	  this.each(function () {
	      // Execute the code logic}); }; })(jQuery); $(the selector). MyPlugins (} {parameter);Copy the code
18 Array merge and resort
let arr1 = [1.25.2.26.1234.6.213];
let arr2 = [2.6.2134.6.31.623];
let c = [...new Set([...arr1, ...arr2])].sort((a, b) = > {
	return a - b;
});
Copy the code
19 call apply

Use: When a function is called, it changes the context in which the function is executed, i.e., the value of this: Call takes an indefinite list of arguments, while apply uses an array of arguments. Performance optimization diagram

20 for setTimeOut

You want to create different loop copies for the loop questions

21 sort function

The V8 sort function only gives two kinds of sort, InsertionSort and QuickSort. Arrays smaller than 10 use insert, and arrays larger than 10 use QuickSort.

22 navigator

23 jquery Binding mode
  1. Click the latter overlay
  2. Bind the latter overlay
  3. On (jquery > = 1.7)
  4. live
  5. delegate
24 Event Flow
  1. Bubble: Child nodes bubble layer by layer to the root node
  2. The capture order is reversed from that of bubbling
  3. The last parameter of addEventListener is true, which means capture, and vice versa
  4. Blocking bubbles does not stop parent node capture
25 Native operation class
// Check whether there is any
function hasClass(ele, cls) {
	return ele.className.match(new RegExp("(\\s|^)" + cls + "(\\s|$)"));
}

/ / add
function addClass(ele, cls) {
	if (!this.hasClass(ele, cls)) ele.className += "" + cls;
}

/ / delete
function removeClass(ele, cls) {
	if (hasClass(ele, cls)) {
		let reg = new RegExp("(\\s|^)" + cls + "(\\s|$)");
		ele.className = ele.className.replace(reg, ""); }} Html5 added a series of classList operations compatible with IE10Copy the code

DOM related

Dom event Model

DOM event models are divided into script model, inline model (one of the same class, the latter covers), dynamic binding (multiple of the same class) demo

<body> <! <button onclick="javascrpt:alert('Hello')">Hello1</button> <! --> <button onclick="showHello()"> </button> <! < span style =" box-sizing: border-box; color: RGB (50, 50, 50); line-height: 20px; font-size: 13px! Important; word-break: break-word! Important;" Function shoeHello() {alert("Hello"); function shoeHello() {alert("Hello"); } var btn3 = document.getElementById("btn3"); btn3.onclick = function () { alert("Hello"); } /*DOM2: you can add multiple events to the same element */ btn3.addeventListener ("click",function () {alert("hello1"); }); btn3.addEventListener("click",function () { alert("hello2"); }) if (btn3.attachEvent){ /*IE*/ btn3.attachEvent("onclick",function () { alert("IE Hello1"); }) }else { /*W3C*/ btn3.addEventListener("click",function () { alert("W3C Hello"); }) } </script>Copy the code

Bubbling explanation: When clicking on an element triggers an event. Events first enter from the outermost parent element to the triggered element layer by layer, and then return from the triggered element layer by layer to the outermost parent element. The stage from the outermost parent element layer by layer is called event capture stage, and the stage from the innermost parent layer by layer is called event bubble.

Mobile touch events

① TouchStart: trigger when the finger touches the screen ② Touchmove: trigger when the finger slides across the screen ③ Touchend: Trigger when the finger leaves the screen ④ TouchCancel event: Triggered when the system stops tracking touches (this event is rarely used and will not be studied in depth). Other events, such as phone access or popup message, enter event:

  1. Touches: An array of Touch objects representing the currently traced touches.
  2. TargetTouches: An array of Touch objects specific to the event target.
  3. ChangeTouches: An array of Touch objects that represent what has changed since the last Touch.

Each touch object contains properties

  1. ClientX: Touch the x coordinate of the target in the viewport.
  2. ClientY: Touch the y coordinate of the target in the viewport.
  3. Identifier: Unique ID that identifies the touch.
  4. PageX: Touch the x-coordinate of the target on the page.
  5. PageY: The y coordinate of the touch target in the page.
  6. ScreenX: Touch the x coordinate of the target on the screen.
  7. ScreenY: Touch the y coordinate of the target on the screen.
  8. Target: The target of the DOM node to be touched.
Event delegation

Reference definition: use event bubbling event delegation is, only to specify an event handler, you can manage all of the benefits of a certain type: to repeat the node to add the same operation, reduce the dom interaction, improve performance implementation approach: add event to the parent components, through the event bubbling, screen elements for a given element, and by using the series operator

HTTP related

Common status code

Status code that starts with 2 (request succeeded) indicating that the request was successfully processed.

200 (Successful) The server successfully processed the request. Typically, this means that the server served the requested web page. 201 (created) The request was successful and the server created a new resource. 202 (accepted) The server has accepted the request but has not yet processed it. 203 (Unauthorized information) The server successfully processed the request, but the information returned may have come from another source. 204 (no content) The server successfully processed the request but did not return any content. 205 (Reset content) The server successfully processed the request but did not return anything. The 206 (partial) server successfully processed part of the GET request.

The start of 3 (the request is redirected) indicates that further action is required to complete the request. Typically, these status codes are used for redirection.

300 (Multiple options) The server can perform multiple operations on a request. The server can select an operation based on the requester (User Agent) or provide a list of operations for the requester to select. 301 (Permanent move) The requested page has been permanently moved to the new location. When the server returns this response (a response to a GET or HEAD request), the requester is automatically forwarded to the new location. The 302 (temporary mobile) server is currently responding to requests from web pages in a different location, but the requester should continue to use the original location for future requests. 303 (Look at other locations) The server returns this code when the requester should use a separate GET request for a different location to retrieve the response. 304 (unmodified) The requested page has not been modified since the last request. When the server returns this response, the web page content is not returned. 305 (Use of proxy) The requester can only use the proxy to access the requested web page. If the server returns this response, it also indicates that the requester should use a proxy. 307 (Temporary redirects) The server is currently responding to requests from web pages in a different location, but the requester should continue to use the original location for future requests.

These status codes indicate that the request may be in error, hindering the server’s processing.

400 (Error request) The server does not understand the syntax of the request. The 401 (unauthorized) request requires authentication. The server may return this response for a web page that requires login. 403 (Disabled) The server rejected the request. 404 (not found) The server could not find the requested page. 405 (Method disabled) Disables the method specified in the request. 406 (not accepted) Unable to respond to the requested web page using the requested content feature. 407 (Requires proxy authorization) This status code is similar to 401 (not authorized), but specifies that the requester should authorize the use of the proxy. 408 (Request timeout) A timeout occurred while the server was waiting for the request. 409 (Conflict) The server is in conflict while completing the request. The server must include information about the conflict in the response. 410 (Deleted) The server returns this response if the requested resource has been permanently deleted. 411 (valid length required) The server will not accept requests that do not contain a valid content-length header field. 412 (Prerequisite not met) The server did not meet one of the prerequisites set by the requester in the request. 413 (Request entity too large) The server cannot process the request because the request entity is too large for the server to handle. 414 (Requested URI too long) The requested URI (usually the url) is too long for the server to process. 415 (unsupported media type) The requested format is not supported by the requested page. 416 (Request scope is not acceptable) If the page cannot provide the requested scope, the server returns this status code. 417 (unmet expectation) The server does not meet the requirements for the “expected” request header field.

Start with 5 (Server error) These status codes indicate an internal error occurred while the server was trying to process the request. These errors may be the fault of the server itself, rather than the request.

500 (server internal error) The server encountered an error and was unable to complete the request. 501 (not implemented) The server does not have the capability to complete the request. For example, the server might return this code when it cannot recognize the request method. 502 (Error gateway) The server acting as a gateway or proxy received an invalid response from the upstream server. 503 (Service unavailable) The server is currently unavailable (due to overloading or down for maintenance). Usually, this is a temporary condition. 504 (Gateway timeout) The server acts as a gateway or proxy, but does not receive the request in time from the upstream server. 505 (HTTP version not supported) The server does not support the HTTP protocol version used in the request.

The cache
  1. Expires is used in Http1.0 and is inconsistent with server time, and is replaced by cache-control in 1.1
The difference between cache-control and Etag

The following figure

Cookie sessionStorage localStorage

Common: Both are stored in the browser and are homologous. Difference: Cookie data is always carried in the same HTTP request, that is, the cookie is passed back and forth between the browser and the server. SessionStorage and localStorage do not automatically send data to the server and only save the data locally. Cookie data cannot exceed 4K (suitable for storing small data). SessionStorage and localStorage have large capacities and different data validity periods. SessionStorage: takes effect only before the current browser window closes. LocalStorage: always valid, the window or browser closed has been saved, you need to manually clear; A cookie is valid only until the set cookie expiration time, even if the window or browser is closed. Different scopes. SessionStorage is not shared in different browser Windows. LocalStorage is shared in all the same source Windows; Cookies are also shared across all the same origin Windows.

Application scenario: localStorage: used for long-term login (+ to determine whether the user has logged in). It is suitable for storing data on the localStorage for a long time. SessionStorage: sensitive account log in at one time. Cookies interact with the server.

GET the POST difference

Request line, request header, request body detail

Cross-domain, JSONP, CORS, postMessage

Description of cross-domain: The domain that initiates a request is different from the domain where the resource to which the request is directed resides. Domain here refers to such a concept: we think that if the protocol, domain name and port number are the same, then it is the same domain. The following table

The json implementation

Native <script> var script = document.createElement('script'); script.type = 'text/javascript'; / / implementation of preach the cords and specify the callback function for onBack script. The SRC = 'http://www.domain2.com:8080/login?user=admin&callback=onBack'; document.head.appendChild(script); Function onBack(res) {alert(json.ify (res)); } </script> jquery $.ajax({ url: 'http://www.domain2.com:8080/login', type: 'get', dataType: JsonpCallback: "onBack", // custom callback function name data: {}}); vue this.$http.jsonp('http://www.domain2.com:8080/login', { params: {}, jsonp: 'onBack' }).then((res) => { console.log(res); }) const queryString = require(' queryString '); const http = require('http'); const server = http.createServer(); server.on('request', function(req, res) { var params = qs.parse(req.url.split('? ') [1]); var fn = params.callback; Res. writeHead(200, {' content-type ': 'text/javascript'}); res.write(fn + '(' + JSON.stringify(params) + ')'); res.end(); }); server.listen('8080'); Jsoup disadvantages can only implement GET requestsCopy the code

CORS: Cross-origin Resource Sharing(CORS), usually server Settings, if cookie request, Response. SetHeader (” access-control-allow-origin “, “www.domain1.com”); SetHeader (” access-control-allow-Credentials “, “true”); // If there are ports that need to write all (protocol + domain name + port), Allow those external requests Response.setheader (” access-control-allow-Credentials “, “true”); // Whether validation is required

Front end of the sample

nativevar xhr = new XMLHttpRequest(); // Ie8/9 requires compatibility with window.XDomainRequest
// The front end sets whether to include cookies
xhr.withCredentials = true;
xhr.open('post'.'http://www.domain2.com:8080/login'.true);
xhr.setRequestHeader('Content-Type'.'application/x-www-form-urlencoded');
xhr.send('user=admin');
 
xhr.onreadystatechange = function() {
    if (xhr.readyState == 4 && xhr.status == 200) {
        alert(xhr.responseText);
    }

jquery
$.ajax({
    ...
   xhrFields: {
       withCredentials: true    // The front end sets whether to include cookies
   },
   crossDomain: true.// Will make the request header contain additional cross-domain information, but not cookies. });Copy the code
The postMessage(data, Origin) method takes two arguments demo A.html <iframe id="iframe" src="http://www.domain2.com/b.html" style="display:none;"></iframe>
<script>       
    var iframe = document.getElementById('iframe');
    iframe.onload = function() {
        var data = {
            name: 'aym'
        };
        // Send cross-domain data to Domain2
        iframe.contentWindow.postMessage(JSON.stringify(data), 'http://www.domain2.com');
    };
 
    // Accept the data returned by Domain2
    window.addEventListener('message'.function(e) {
        alert('data from domain2 ---> ' + e.data);
    }, false);
</script><script>// Receive data from Domain1
    window.addEventListener('message'.function(e) {
        alert('data from domain1 ---> ' + e.data);
 
        var data = JSON.parse(e.data);
        if (data) {
            data.number = 16;
 
            // After processing, send back to Domain1
            window.parent.postMessage(JSON.stringify(data), 'http://www.domain1.com'); }},false);
</script>
Copy the code
The osi model

Seven layers: physical layer, data link layer, network layer, transport layer, session layer, presentation layer, and application layer TCP UCP belongs to the transport layer. HTTP belongs to the application layer

Http2.0 http1
  1. The basic unit of HTTP2.0 is the binary frame
  2. Frames in HTTP2.0 have priority
  3. Multiplexing in HTTP2.0 (1 connection)
  4. HTTP2.0 compresses message headers
  5. HTTP2.0 server push
  6. HTTP2.0 is only applicable to HTTPS scenarios

Vue related

Lifecycle order

Component communication

2. Emit props (props). Emit props (props)

Vuex

Mutations synchronous operation is used to change the state. It is not recommended that an asynchronous action execute multiple Mutaions. Official Examples of asynchronous operations mapState, mapGetters, and mapActions are recommended

<template> <el-dialog :visible.sync="show"></el-dialog> </template> <script> import {mapState} from 'vuex'; Export default {computed:{// The three points here are called: extension operator... MapState ({show:state=>state.dialog.show}),}} </scriptCopy the code
VueRouter
definevar routes = [
    {
        path:"/one".component: Components to be imported1
    },
    {
        path:"/two".component: Components to be imported2},];// Define the routing component
var router = new VueRouter({
    routes
});
// Define the route
new Vue({
    el:"#box", router }); <router-view></router-view> is replaced with the corresponding template HTML access mode <router-link to="/one"> one </router-link>(similar to a tag) JS access mode this.$router.push('/one'); The value of the replace parameter can be obtained by this.$route.query.xxxxCopy the code
Vue bidirectional binding

How it works: the object.defineProperty () method is used to redefine the operation of the Object to get and set the property value. Disadvantages: bidirectional data flow is automatic state management, but in practical applications there will be a lot of logic that has to deal with state changes manually, which makes the program complexity rise and difficult to debug.

computed watch methods

Usage: distinguish:

  1. The first two automatically trace data, execute related functions, and the last one is called manually;
  2. Computed is a computing attribute and its usage is the same as that of data
  3. Watch acts like an event listener, performing operations when an object changes
  4. Methods are similar to execution methods in JS
  5. For computed, only get attributes are available
  6. If asynchronous operation is performed at the same time as data changes or there is relatively large overhead, watch is the best choice
  7. The object of watch must be declared in advance

Algorithm related

Various sorting implementations

The relevant data

// Bubble sort: compare two adjacent items. If the first is larger than the second, swap their positions, and move the items up to the correct order, as if bubbles were risingThe bubbling demo:function bubbleSort(arr) {
    let len = arr.length;
    for (let i = 0; i < len; i++) {
        for (let j = 0; j < len - 1 - i; j++) {
            if (arr[j] > arr[j+1]) {        // Compare adjacent elements in pairs
                [arr[j + 1], arr[j]] = [arr[j], arr[j + 1]]. }}}return arr;
}
// 1) First, select an intermediate item in the array as the main element
// 2) Create two Pointers, the one on the left pointing to the first item in the array, the one on the right pointing to the last item, move the left pointer until an item larger than the pivot is found, then move the right pointer until an item smaller than the pivot is found, and swap them. Repeat the process until
// The left pointer exceeds the right pointer. This makes everything smaller than the pivot entry on the left, and everything larger than the pivot entry on the right. This step is called partitioning
// 3) Next, the algorithm repeats the previous two steps for the partition of the smaller array (smaller array of values smaller than the principal element, and smaller array of values larger than the principal element) until the sorting is completeFast row demo:function quickSort(arr, left, right) {
    let len = arr.length;
    let partitionIndex;
    left = typeofleft ! = ='number' ? 0 : left;
    right = typeofright ! = ='number' ? len - 1 : right;
    if (left < right) {
        partitionIndex = partition(arr, left, right);
        quickSort(arr, left, partitionIndex - 1);
        quickSort(arr, partitionIndex + 1, right);
    }
    return arr;
}

function partition(arr, left, right) {     // Partition operation
    let pivot = left;                      // Set the pivot value.
    let index = pivot + 1;
    for (let i = index; i <= right; i++) {
        if (arr[i] < arr[pivot]) {
            [arr[i], arr[index]] = [arr[index], arr[i]];
            index++;
        }
    }
    [arr[pivot], arr[index - 1]] = [arr[index - 1], arr[pivot]];
    return index - 1;
}
// Select sort: the idea is to find the smallest one first, find the second smallest one second, and so on.Select the demo:function selectionSort(arr) {
	let len = arr.length;
	let minIndex;
	for (let i = 0; i < len - 1; i++) {
		minIndex = i;
		for (let j = i + 1; j < len; j++) {
			if (arr[j] < arr[minIndex]) {     // Look for the smallest number
			    minIndex = j;                 // Save the index with the smallest number
		    }
		}
		[arr[i], arr[minIndex]] = [arr[minIndex], arr[i]];
	}
return arr;
}
// Insert sort: sort the items one at a time, assuming the first item is sorted. Then, compare the second item with the first item, whether the second item should be inserted before or after the first item, and whether the third item should be inserted before or after the first item, or the third itemInsert the demo:function insertionSort(arr) {
	let len = arr.length;
	let preIndex, current;
	for (let i = 1; i < len; i++) {
	    preIndex = i - 1;
	    current = arr[i];
	    while (preIndex >= 0 && arr[preIndex] > current) {
		    arr[preIndex + 1] = arr[preIndex];
		    preIndex--;
	    }
	    arr[preIndex + 1] = current;
	}
	return arr;
}
// Merge sort: Mozilla Firefox uses merge sort as an implementation of array.prototype.sort, while Chrome uses a variant of Quicksort. The first three algorithms don't perform well, but merge sort does well.
Merge sort is a dive-and-conquer algorithm. So essentially you take the original array and you slice it up into smaller arrays, until each of them has only one position, and then you merge the smaller arrays into larger arrays, and you sort through the merging process, until you have only one larger array that's sortedMerge the demo:function mergeSort(arr) {  // Take a top-down recursive approach
    let len = arr.length;
    if(len < 2) {
        return arr;
    }
    let middle = Math.floor(len / 2),
    left = arr.slice(0, middle),
    right = arr.slice(middle);
    return merge(mergeSort(left), mergeSort(right));
}

function merge(left, right){
    let result = [];
    while (left.length && right.length) {
        if (left[0] <= right[0]) {
            result.push(left.shift());
        } else{ result.push(right.shift()); } } result.push(... left); result.push(... right);return result;
}
// Heapsort: Heapsort is named after sorting binary trees in an array.
// 1) index 0 is the root node of the tree; 2) the parent node of any node N is N/2; 3) The left child node of node L is 2*L; 4) The right child node of node R is 2*R + 1
// In essence, you build a binary tree, then swap the root node with the last one, and then build the remaining binary tree, swapping until the last one is leftHeap demo:var len;    // Since multiple declared functions require data length, set len to a global variable

function buildMaxHeap(arr) {   // Create the big top heap
    len = arr.length;
    for (let i = Math.floor(len / 2); i >= 0; i--) { heapify(arr, i); }}function heapify(arr, i) {     / / heap of adjustment
    let left = 2 * i + 1;
    let right = 2 * i + 2;
    let largest = i;
    if (left < len && arr[left] > arr[largest]) {
        largest = left;
    }
    if (right < len && arr[right] > arr[largest]) {
        largest = right;
    }
    if (largest !== i) {
        [arr[i], arr[largest]] = [arr[largest], arr[i]];
        heapify(arr, largest);
    }
}

function heapSort(arr) {
    buildMaxHeap(arr);
    for (let i = arr.length - 1; i > 0; i--) {
        [arr[0],arr[i]]=[arr[i],arr[0]];
        len--;
        heapify(arr, 0);
    }
    return arr;
}
Copy the code
Binary search

(1) First, start the search from the middle element of the ordered array, if the element is the target (that is, the element to look for), the search process is finished, otherwise proceed to the next step. (2) If the target element is greater or less than the middle element, look for the half of the array that is greater or less than the middle element, and repeat the first step. (3) If a step array is empty, the target element cannot be found.

// Non-recursive algorithm
function binary_search(arr, key) {
    let low = 0;
    let high = arr.length - 1;
    while(low <= high){
        let mid = parseInt((high + low) / 2);
        if(key === arr[mid]){
            return  mid;
        }else if(key > arr[mid]){
            low = mid + 1;
        }else if(key < arr[mid]){
            high = mid - 1;
        }else{
            return - 1; }}}// Recursive algorithm
function binary_search(arr,low, high, key) {
    if (low > high){
        return - 1;
    }
    let mid = parseInt((high + low) / 2);
    if(arr[mid] === key){
        return mid;
    }else if (arr[mid] > key){
        high = mid - 1;
        return binary_search(arr, low, high, key);
    }else if (arr[mid] < key){
        low = mid + 1;
        returnbinary_search(arr, low, high, key); }};Copy the code
Binary tree correlation
createfunction Node(data,left,right){
	this.data = data;/ / values
	this.left = left;/ / the left node
	this.right = right;/ / right node}; Insert the binary treefunction insert(node,data){
	// Create a new node
	let newNode  = new Node(data,null.null);
	// Check whether the root node exists and no new node is saved
	if(node == null){
		node = newNode;
	}else{
		// Obtain the root node
		let current = node;
		let parent;
		while(true) {// Save the current node as the parent node
			parent = current;
			// Put the small data in the left node
			if(data < current.data){
				// Get the left node of the current node
				// Check whether the left node under the current node has data
				current = current.left;
				if(current == null) {// If there is no data, store the new node to the left node under the current node
					parent.left = newNode;
					break; }}else{
				current = current.right;
				if(current == null){
					parent.right = newNode;
					break; }}}}} Flip the binary treefunction invertTree(node) {
	if(node ! = =null) {
		node.left, node.right = node.left, node.right;
		invertTree(node.left);
		invertTree(node.right);
	}
	return node;
}
Copy the code
Find the KTH node from the bottom of the list2A train of thought1: first iterates the length, and then finds the length -k+1The value of the2:2One pointer, one pointer goes first k- 1And then both of them go to the bottom, and the latter is the resultCopy the code

Network Security Related

XSS CSRF

XSS(cross-site scripting attack), malicious injection of HTML code, other users access, will be executed features: can inject malicious HTML/JavaScript code to the user browse the web page, so as to achieve Cookie data theft, session hijacking, phishing and other attack defense means:

  • The browser prohibits the page’s JS from accessing cookies with the HttpOnly attribute
  • Check the input format on both ends
  • CSRF(Attack cross-site Request Forgery) features: All parameters of important operations can be guessed by attackers. The attacker can predict all the parameters and parameter values of the URL to successfully construct a forged request. Means of defense:
  • Token authentication mechanism, such as adding a token to the request data field and verifying its validity when responding to the request
  • Restrictions on user operations, such as verification codes (tedious, poor user experience)
  • Request source restrictions, such as restricting the HTTP Referer to complete the operation (less defensively), are commonly used in practice

Webpack related

##### Packaging volume optimization

  1. Extracting third-party libraries or importing third-party libraries by referring to external files
  2. Code compression plug-in UglifyJsPlugin
  3. Gzip compression is enabled on the server
  4. Load resource file require.ensure on demand
  5. Optimized source-map in DevTool
  6. Strip the CSS file and package it separately
  7. Removing unnecessary plug-ins often means that the development environment and production environment share the same set of configuration files, resulting in ##### packaging efficiency
  8. The development environment is built incrementally, enabling hot updates
  9. The development environment does not do meaningless work such as extracting hashes from CSS computing files
  10. Configuration devtool
  11. Select an appropriate loader
  12. Enable cache for some loaders, such as Babel-Loader
  13. Third-party libraries are imported
  14. Extract common code
  15. The search path at optimized build time indicates the directory that needs to be built and the directory that does not need to be built
  16. Modularity introduces the required parts
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. And, this function can be used by supplying it withthisContext access to the Loader API. Reverse - TXT - loader definitionmodule.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}'`;
}
使用
{
	test: /\.txt$/.use: [{'./path/reverse-txt-loader'}},Copy the code
plugins

The use is broader, usually requiring only require() and adding it to the plugins array with a new one

other

What happens to the URL to the interface display
  1. For DNS resolution, the local cache first searches for the IP address, and then searches for the IP address layer by layer. The basic order of DNS resolution is as follows: Local DNS server -> root DNS server ->com TOP-LEVEL DNS server And so on, record and cache the information. For example, www.google.com:. ->.com -> google.com. -> www.google.com.
  2. TCP connection three-way handshake, as long as no acknowledgement message will be resend
    1. The host sends a connection request to the server (hello, I want to know you);
    2. The server receives the request and sends a signal agreeing to connect (ok, nice to meet you);
    3. After receiving the signal of consent to connect, the host sends a confirmation signal to the server again (nice to meet you, too), and the connection is established between the host and the server.
  3. Send AN HTTP request The browser analyzes the URL and sets the request packet to be sent. A request packet contains a request line, request header, blank line, and request body. The default HTTPS request port is 443 and the default HTTP request port is 80. Common HTTP requests are as follows
POST/HTTP1.1 Host:www.wrox.com User-agent :Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; The.net CLR 2.0.50727; The.net CLR 3.0.04506.648; NET CLR 3.5.21022) Content-type: Application/x-wwW-form-urlencoded content-length :40 Connection: Keep-alive name=Professional%20Ajax& Publisher =Wiley Part 2: Request header, lines 2 through 6. Part three: blank line, blank line 7. Part four: Request data, line 8. 4. The server processes the request and returns an HTTP packetCopy the code
HTTP/1.1 200 OK Date: Fri, 22 May 2009 06:07:21 GMT Content-type: text/ HTML; charset=UTF-8<html>
      <head></head>
      <body>
            <! --body goes here-->
      </body>
</html>The first behavior status line, (HTTP/1.1) indicates that the HTTP version is version 1.1, the status code is 200, the status message is (OK) the second line and the third behavior message headers, Date: The Date and time to generate the response; Content-type: specifies the MIME Type of HTML(text/ HTML). The encoding Type is UTF-8. The HTML section following the blank line is the body of the response.Copy the code
  1. The browser parses the rendered page
  • The HTML parser parses THE HTML document to build a DOM Tree, and the CSS parser parses the CSS in HTML to build Style Rules. The combination of the two forms an Attachment.
  • Construct a Render Tree with Attachment
  • When the Render Tree is built and you enter the Layout /reflow phase, each phase will be assigned an exact coordinate that should appear on the screen.
  • Finally, after all the nodes are drawn, a page is displayed. The execution stops when a script is encountered, so it is usually placed at the bottom
  1. Connect the end of the
Component packaging

Purpose: For reuse, improve development efficiency and code quality Note: Low coupling, single responsibility, reusability, maintainability

  1. Analysis of the layout
  2. Preliminary development
  3. Change numerous for brief
  4. Component abstraction
JS asynchronous loading
  1. Dynamically generate script tags
  2. Add h5’s async defer property, which is out of order and not suitable for dependency loading
  3. Async is “execute as soon as download” and defer is “execute as soon as render”
CSS and JS animation differences
  1. CSS performance is good
  2. The CSS code logic is relatively simple
  3. Js animation control is good
  4. Good JS compatibility
  5. Js can achieve more animation
  6. Js can add events
Load balancing

Multiple servers work together so that one or several of them are not overworked to maximize the function of the server

  1. HTTP redirection load balancing: The scheduler selects a server based on the policy to respond to requests with 302. The disadvantages are only effective the first time, and subsequent operations remain on the server
  2. DNS load balancing: Access to one of multiple IP servers during domain name resolution (poorly monitored)
  3. Reverse proxy load balancing: The server accesses a unified server, and the server schedules the access to a specific server. This requires a large number of unified servers, and performance depends on the number of server farms
CDN

Content distribution network, the basic idea is to avoid as far as possible on the Internet may affect the speed and stability of data transmission bottlenecks and links, so that the content transmission faster and more stable.

A memory leak

Definition: the program has been dynamically allocated heap memory for some reason the program is not released or cannot be released caused by a variety of problems in JS possible memory leak result: slow, crash, delay and other reasons:

  1. The global variable
  2. When the DOM is emptied, the reference still exists
  3. Closures are used in IE
  4. Timer not cleared
  5. Memory leak caused by the presence of child elements

Avoidance strategies:

  1. Reduce unnecessary global variables, or objects with a long life cycle, and timely garbage collection of useless data;
  2. Pay attention to program logic, avoid “infinite loop” and so on;
  3. Rule of Avoiding creating too many objects: Return things when you don’t use them.
  4. Reduce the level of excessive references
Babel principle

ES6, 7 code input -> parse -> get AST -> plugin with babel-traverse traverse traverse to get new AST -> generate ES5 code from AST tree with babel-generator

promise

Properties: The error of a Promise object bubbles and is passed back until it is caught, i.e. the error is always caught by the next catch statement

Js custom events

Document.createevent () Event.initEvent () Element.dispatchEvent ()

Demo: (en: custom event name, fn: event handler, addEvent: adding custom events to DOM elements, triggerEvent: triggering custom events)window.onload = function(){
    var demo = document.getElementById("demo");
    demo.addEvent("test".function(){console.log("handler1")});
    demo.addEvent("test".function(){console.log("handler2")});
    demo.onclick = function(){
        this.triggerEvent("test");
    }
}
Element.prototype.addEvent = function(en,fn){
    this.pools = this.pools || {};
    if(en in this.pools){
        this.pools[en].push(fn);
    }else{
        this.pools[en] = [];
        this.pools[en].push(fn);
    }
}
Element.prototype.triggerEvent  = function(en){
    if(en in this.pools){
        var fns = this.pools[en];
        for(var i=0,il=fns.length; i<il; i++){ fns[i](); }}else{
        return; }}Copy the code
Es6 module CommonJS AMD CMD
  1. In the CommonJS specification, each JavaScript file is a separate module context, within which properties created by default are private. That is, variables defined in one file (including functions and classes) are private and not visible to other files.
  2. CommonJS is a synchronously loaded module and will cause congestion in the browser, so it is not applicable
  3. AMD asynchronous, need to define callback define mode
  4. In ES6, a module is a separate file, and all variables inside the file are not available externally. If you want a variable inside the module to be read externally, you must export the variable using the export keyword
  5. Es6 can also export classes and methods to automatically apply strict mode
Routing differences between the front and rear ends

In fact, the front-end route is just JS to operate the DOM element according to the URL, according to the needs of each page to the server to request data, returned data and template combination.

Understand dug 👉 autumn autumn recruit the campaign more job information for job searching, with a gifts | the nuggets skill in writing essay