Symmetric encryption and asymmetric encryption

Symmetric encryption and decryption use the same key. In the encryption process, ciphertext can be transmitted using the original text + the key, and in the decryption process, the original text can be derived using the ciphertext + the key. However, asymmetric encryption uses two keys. Generally, public keys are used for encryption and private keys are used for decryption.

The basic concept

Digital certificate: The CA uses its own private key, encrypts the sender’s public key along with some related information, and generates a “digital certificate”

Digital signature: Using the Hash function, a digest of the content sent is generated. Then, using the private key, the digest is encrypted to generate a “digital signature”.

Encryption process based on public key

For example, there are two users, Alice and Bob. Alice wants to send a piece of plaintext to Bob through the two-key encryption technology, and Bob has a pair of public and private keys. The encryption and decryption process is as follows:

  1. Bob sends his public key to Alice.
  2. Alice encrypts her message with Bob’s public key and sends it to Bob.
  3. Bob uses his private key to decrypt Alice’s message.

Public key based authentication process

Authentication and encryption are different. The primary user authenticates the user. As long as we can verify that a user’s private key is correct, we can verify the authenticity of the user.

Alice wants Bob to know that she is real Alice, not fake. Therefore, Alice only needs to use public key cryptography to sign the file and send it to Bob, and Bob uses Alice’s public key to decrypt the file. If the decryption succeeds, It is proved that Alice’s private key is correct, so the identification of Alice is completed. The entire identity authentication process is as follows:

  1. Alice signs the file by encrypting it with her private key.
  2. Alice sends the signed file to Bob.
  3. Bob decrypts the file with Alice’s public key to verify the signature.

HTTP hijacking and DNS hijacking

HTTP hijacked

HTTP hijacking: The IP address of the domain name resolved by your DNS does not change. Hijacking your request while interacting with the site. The website returns the request to you before it sends you the message.

23. XSS and CSRF

XSS

Cross Site Scripting, full name for Cross Site Scripting, is an attack called cross-site Scripting, where hackers embed malicious Scripting code into pages to steal user information.

Typically, XSS attacks are implemented in three ways — storage, reflection, and documentation. The principle is relatively simple, first to introduce one by one.

Storage type

Stored, as the name implies, stores malicious scripts. Indeed, stored XSS stores the scripts in the server’s database, and then executes the scripts on the client side to achieve the effect of attack.

The common scenario is to submit a script code in the comment area. If the back and forth end has not done a good job of escaping, the comment content is stored in the database and executed directly in the page rendering process. It is equivalent to executing a section of JS code with unknown logic, which is very scary. This is a stored XSS attack.

reflective

Reflective XSS refers to malicious scripts as part of a network request.

For example, if I type:

http://sanyuan.com?q=<script>alert(" You're screwed ")</script> Copy the codeCopy the code

In this case, the server takes the q argument and sends it back to the browser, which parses it as part of the HTML, discovers it’s a script, executes it, and is attacked.

It is called reflective because malicious scripts are parsed through the server as parameters to a network request and then reflected back into an HTML document. Unlike the stored type, the server does not store these malicious scripts.

The document type

Document-type XSS attacks do not go through the server side, but act as a middleman, hijacking network packets during data transfer and modifying the HTML document inside!

Such hijackings include WIFI router hijackings or local malware.

Measures to prevent

Understanding how the three XSS attacks work, we can see one thing in common: they all allow malicious scripts to be executed directly in the browser.

The way to prevent it, then, is to avoid the execution of these scripts.

In order to accomplish this, one belief and two uses must be achieved.

A belief

Never trust any user input!

Both on the front-end and server side, user input should be transcoded or filtered.

Such as:

<script>alert('You're screwed.')</script>
Copy the code

After transcoding, it becomes:

&lt; script&gt; alert(&#39; You're screwed39;) &lt; /script&gt;Copy the code

Using the CSP

CSP is a content security policy in the browser. The core idea of CSP is that the server decides which resources the browser loads. Specifically, it can accomplish the following functions:

  1. Restrict resource loading in other domains.
  2. Disallow data submission to other domains.
  3. Provide a reporting mechanism to help us detect XSS attacks in a timely manner.

The instance

A web site manager wants all content to come from the same source on the site (excluding subdomains)

Content-Security-Policy: default-src 'self'
Copy the code

A site manager allows content from trusted domain names and their subdomains (domain names do not have to be the same as the domain where the CSP is set up)

Content-Security-Policy: default-src 'self' *.trusted.com
Copy the code

Using the HttpOnly

Many XSS attack scripts are used to steal cookies, and after setting the HttpOnly attribute of cookies, JavaScript cannot read the value of cookies. This is also a good defense against XSS attacks.

CSRF

Cross-site request Forgery, as the name implies, is a hacker disguised as a user identity to perform some malicious and illegal operations that the user does not want

You might do three things. The list is as follows:

1. Automatically send GET requests

A hacker’s web page might contain a code like this:

<img src="https://xxx.com/info?user=hhh&count=100">
Copy the code

When you enter the page, you automatically send a get request. Note that this request is automatically accompanied by a cookie information about xxx.com (this assumes that you are already logged in to xxx.com).

If the server does not have the corresponding authentication mechanism, it may think that the user sending the request is a normal user, because it carries the corresponding cookie, and then carries out the corresponding various operations, such as transfer of money and other malicious operations.

2. Automatically sends a POST request

The hacker could have filled out a form and written an auto-submission script.

<form id='hacker-form' action="https://xxx.com/info" method="POST">
  <input type="hidden" name="user" value="hhh" />
  <input type="hidden" name="count" value="100" />
</form>
<script>document.getElementById('hacker-form').submit();</script>
Copy the code

It will also carry the corresponding user cookie information, so that the server mistakenly thinks that it is a normal user in the operation, so that all kinds of malicious operations become possible.

3. Induced click to send GET request

On a hacker’s website, a link may be posted that urges you to click:

<a href="https://xxx/info? user=hhh&count=100" taget="_blank">Click to enter the fairy world</a>
Copy the code

Click and automatically send a GET request.

This is how CSRF attacks work. Compared with XSS attack, CSRF attack does not need to inject malicious code into THE HTML document of the user’s current page, but jump to a new page, and simulate the user’s operation by taking advantage of the authentication vulnerability of the server and the user’s previous login status.

Measures to prevent

1. Take advantage of the SameSite property of the Cookie

An important part of a CSRF attack is to automatically send a Cookie under the target site, and then this Cookie simulates the user’s identity. Therefore, Posting on cookies is the best defense.

As it happens, there is one key field in cookies that places some restrictions on how cookies can be carried in requests: SameSite.

SameSite can be set to three values, Strict, Lax, and None.

A. In Strict mode, the browser completely forbids third-party requests to carry cookies. For example, sanyuan.com can only carry cookies in the domain name of Sanyuan.com, but not in other websites.

B. In Lax mode, the Cookie can only be carried if the GET method submits a form condition or the A tag sends a GET request.

C. In None mode, which is the default mode, requests automatically carry cookies.

2. Verify the source site

This requires two fields in the request header: Origin and Referer.

Origin contains only domain name information, while Referer contains the specific URL path.

Of course, both of these can be forged by customizing the request headers in Ajax, which is less secure.

3. CSRF Token

Django is a backend framework for Python. If you’ve developed with Django, you’ll know that its template is often accompanied by a line of code like this:

{% csrf_token %}
Copy the code

This is a typical application of the CSRF Token. So how does it work?

First, when the browser sends a request to the server, the server generates a string and implants it into the returned page.

Then the browser, if it wants to send a request, must carry the string, and the server verifies that it is valid and does not respond if it is not. This string is known as a CSRF Token, which is usually not available to third-party sites and is therefore rejected by the server.

24, Hump naming and underline interchange algorithm

// Underline convert hump
function toHump(name) {
    return name.replace(/\_(\w)/g.function(all, letter){
        return letter.toUpperCase();
    });
}
// Hump conversion underline
function toLine(name) {
  return name.replace(/([A-Z])/g."_ $1").toLowerCase();
}
Copy the code

The difference between animation and Transition

The difference between:

1. Transition is a process of changing style values, only a beginning and an end. Animation is also called keyframe. By combining animation with keyFrame, you can set a state of the middle frame.

Animation and @KeyFrame can trigger this process without triggering the time, while Transition needs to trigger the hover or JS event.

3. The animation can set many properties, such as the number of cycles, the state at the end of the animation, and so on.

Animation can set each frame with the KeyFrame, but Transition only has two frames.

5. In terms of performance: the browser has a main thread and a layout thread; The main thread is generally running on JS, page layout, bitmap generation, and so on, and then the generated good bitmap to the layout thread, and the layout thread will draw the bitmap to the page through THE GPU, will also request the bitmap to the main thread, and so on; When we use aniamtion, we can change many properties, such as width, height, postion and so on. When we change the properties of the document flow, the page will be backflow and redraw, which has a great impact on performance. But when we use transition, we usually use tansfrom to rotate and scale and so on. It doesn’t create a new bitmap, and it doesn’t rearrange the page.

26. Key is related in VUE

The Diff algorithm

When the data on a page changes, the Diff algorithm only compares nodes at the same level:Copy the code

If the node type is different, the previous node is killed, and new nodes are created and inserted without comparing subsequent children of this node.

If the node type is the same, the attributes of the node are reset to update the node.

When there are many identical nodes in a certain layer, that is, list nodes, the update process of Diff algorithm also follows the above principle by default.Copy the code

For example, in this case:

We want to add an F between B and C. The Diff algorithm defaults to this:

Is it inefficient to update C to F, D to C, E to D, and then insert E? Therefore, we need to use key to make a unique identification for each node, so that the Diff algorithm can correctly identify this node and find the correct location area to insert a new node.

Disadvantages of using index for key

The problem caused by the addition and deletion is that the previous data and the re-rendered data cannot be associated with the change of the key value. That would lose the point of the key. It is also the culprit that causes the data to appear strange!

27, 8 data types of JS

JS data types: How many types of JS data are there?

Eight. Boolean, Null, undefined, object, symbol, bigInt.

Although typeof NULL ==’Object’ it is not an Object

Null is not actually an object, and although typeof NULL outputs object, this is actually a bug. In the original version of JS, the 32-bit system was used. For performance reasons, the type information of the low-value stored variable was used. The beginning of 000 is represented as the object type, whereas null is all zeros, so NULL is judged as the object type.

Simple and non-simple requests

Browsers divide CORS requests into two types: simple request and not-simple request. Simple request browsers do not precheck, while non-simple request prechecks. How do you distinguish between these two methods?

If the following three conditions are met at the same time, it is a simple request; otherwise, it is a non-simple request

1. The request mode can be GET, POST, or HEAD

2. The HTTP request header contains the Accept, Accept-language, Content-language, Content-Type, and last-event-ID fields

3.Content-type can only be: Application/X-www-form-urlencoded, multipart/form-data, text/plain

For simple requests, the browser adds an Origin field in the request header to indicate the source (protocol + domain name + port) from which the request is made. The server uses this value to decide whether to approve the request or not, and the server returns a response with several more header fields, as shown in the figure: Three of the above headers are related to CORS requests, all of which begin with Access-Control-.

Access-control-allow-origin: This field is mandatory. * indicates that any domain name is accepted. You can also specify a domain name

Access-control-allow-credentials: This field is optional and is a Boolean value, indicating whether cookies are allowed. (Note: This field is invalid if access-Control-allow-origin is set to *.)

3. Access-control-allow-headers: This field is optional. Cache-control, Content-Type, Expires, etc. If you want to retrieve other fields, you can specify this field.

Non-simple requests are requests that have special requirements on the server, such as PUT or DELETE, or the content-Type field Type is Application/JSON. An HTTP request is added before formal communication, called precheck. The browser first asks the server if the domain name of the current web page is on the server’s approved list. When the server allows this, the browser issues a formal XMLHttpRequest request; otherwise, an error is reported.

Obviously, the pre-checked request in the request header does not carry cookies, and the formal request carries cookies and parameters. The same fields are added to the response header as in normal requests.

Once the server passes the “precheck” request, every subsequent normal BROWSER CORS request is treated as a simple request.

Implementation of deep copy

1, use the recursive way to achieve deep copy // use the recursive way to achieve deep copy array, object

function deepClone1(obj) {
  // Make a deep copy of an array or an object. If it is an array, make a deep copy of an array or an object
  var objClone = Array.isArray(obj) ? [] : {};
  // The deep copy cannot be empty and is an object or
  if (obj && typeof obj === "object") {
    for (key in obj) {
      if (obj.hasOwnProperty(key)) {
        if (obj[key] && typeof obj[key] === "object") {
          objClone[key] = deepClone1(obj[key]);
        } else{ objClone[key] = obj[key]; }}}}return objClone;
}
Copy the code

2. The perfect version manually implements a deep clone (taking into account special objects such as dates/regees and dealing with circular references)

const isObject = (target) = >
  (typeof target === "object" || typeof target === "function") && target ! = =null;

function deepClone(target, map = new Map(a)) {
  // Check whether the reference type has been copied
  if (map.get(target)) {
    return target;
  }
  // Get the current value constructor: get its type
  let constructor = target.constructor;
  // Check whether the current target object matches the regular and date format object
  if (/^(RegExp|Date)$/i.test(constructor.name)) {
    return new constructor(target); // Create a new instance of a special object (re class/date class)
  }
  if (isObject(target)) {
    map.set(target, true); // Mark the object referenced in the loop
    const cloneTarget = Array.isArray(target) ? [] : {};
    for (let prop in target) {
      if(target.hasOwnProperty(prop)) { cloneTarget[prop] = deepClone(target[prop], map); }}return cloneTarget;
  } else {
    returntarget; }}Copy the code

30, The effect of X-requested-with

Can be used to determine whether a client request is an Ajax request or another request. Req.headers [‘x-requested-with’].tolowerCase () == ‘XMLHttprequest’ is an Ajax request.

Parent/child component lifecycle in VUE

  • Loading the rendering process
Parent beforeCreate-> Parent created-> parent beforeMount-> child beforeCreate-> child created-> child beforeMount-> Child Mounted -> parent MountedCopy the code
  • Child component update process
Parent beforeUpdate-> Child beforeUpdate-> Child updated-> Parent updatedCopy the code
  • Parent component update process
Father father beforeUpdate - > updatedCopy the code
  • Destruction of the process
Parent beforeDestroy-> Child beforeDestroy-> Child destroyed-> Parent destroyedCopy the code

32, The difference between heap and stack

1. Stack space allocation differences

Stack (operating system) : automatically allocated and released by the operating system (compiler) to store function parameter values, local variable values, etc. It operates like a stack in a data structure.

Heap (operating system) : The heap is allocated and released by the programmer. If the programmer does not release the heap, the program may be recycled by the OS at the end of the program. Allocation is similar to a linked list.

2. Stack cache differences

Stacks use level 1 caches, which are usually in storage when called and released immediately.

The heap is stored in a level 2 cache, and its lifetime is determined by the virtual machine’s garbage collection algorithm (objects are not recycled once orphaned). So the speed of calling these objects is relatively low.

Scope chain

First, scope

In Javascript, scopes are divided into global scopes and function scopes

Global scope:

Code can be accessed anywhere in the program, and the window object’s built-in properties have global scope.

Function scope:

Only fixed snippets of code can be accessed

A scope has a hierarchy, which depends on the scope in which the function is created. As above, fn scope creates bar function, so “FN scope” is the superior of “bar scope”.

The greatest use of a scope is to isolate variables. Variables of the same name in different scopes do not conflict.

Variable value: to the scope of the function that created the variable

Scope chain

Normally, a variable takes a value in the scope of the function that created it.

But if no value is found in the current scope, the chain is called the scope chain.

Why isn’t var a global variable in JS

In js, if a variable does not have a var declaration, it is automatically moved to the next level of scope to find the declaration statement of the variable. If it is found, it is used.

Continue to look up, until the global scope, if there is still no declaration of this variable in the global scope, then automatically declared in the global scope, this is

Js is the scope chain, also known as variable promotion

33, closures

The concept of closures

The definition of “closure” in various professional literature is abstract and difficult to understand. My understanding is that closures are functions that can read variables inside other functions.

Because in the Javascript language, only subfunctions inside functions can read local variables, closures can be understood simply as “functions defined inside a function.”

So, in essence, a closure is a bridge between the inside and outside of a function.

The purpose of closures

Closures can be used in many ways. It is useful for reading variables inside functions, as mentioned earlier, and for keeping their values in memory at all times.

How to understand this sentence? Look at the code below.

function f1(){var n=999; nAdd=function(){n+=1}function f2(){alert (n); }returnF2; }varResult = f1 (); result();/ / 999NAdd bring them any closer (); result();/ / 1000
Copy the code

In this code, result is actually the closure f2 function. It runs twice, the first with a value of 999 and the second with a value of 1000. This proves that the local variable n in function f1 is kept in memory and is not automatically cleared after f1 is called.

Why is that? The reason is that F1 is the parent of F2, and F2 is assigned to a global variable, which results in F2 always being in memory, and f2’s existence depends on F1, so F1 is always in memory and not collected by garbage collection when the call ends.

NAdd =function(){n+=1}; nAdd is a global variable, not a local variable. Second, the value of nAdd is an anonymous function, and the anonymous function itself is a closure, so nAdd is a setter that operates outside the function on local variables inside the function.

Considerations for using closures

1) Because closures will cause variables in functions to be stored in memory, which consumes a lot of memory, so do not abuse closures, otherwise it will cause performance problems of web pages, and may lead to memory leaks in IE. The solution is to remove all unused local variables before exiting the function.

2) Closures change the values of variables inside the parent function outside the parent function. So, if you use a parent function as an object, a closure as its Public Method, and internal variables as its private values, be careful not to arbitrarily change the values of the parent function’s internal variables.

var name = "The Window";varobject = {name : "My Object".getNameFunc : function(){return function(){return this.name; }; }}; alert(object.getNameFunc()());//The Window
Copy the code
var name = "The Window";varobject = {name : "My Object".getNameFunc : function(){var that = this;return function(){returnThat. The name; }; }}; alert(object.getNameFunc()());//My Object
Copy the code

34, This points to

The first thing to note is that the reference of this is not determined at function definition. It is only determined at function execution that this refers to. In fact, this refers to the object calling it

Example 1:

The function a here is actually invoked by the Window object

function a(){
    var user = "Chaser";
    console.log(this.user); //undefined
    console.log(this); //Window
}
a();//window.a()
Copy the code

Example 2:

var o = {
    user:"Chaser".fn:function(){
        console.log(this.user);  / / the commitments
    }
}
o.fn();
Copy the code

This refers to object O, because you call fn through o.fin (), so the natural reference is to object O. Again, the reference to this is not determined when the function is created, but only when the function is called.

var o = {
    a:10.b: {a:12.fn:function(){
            console.log(this.a); / / 12
        }
    }
}
o.b.fn();
Copy the code

This is also the object o, but again this does not execute it, so you would say that everything I said in the first place is wrong. In fact, it is not. What I said at the beginning was not accurate. Next, I will add a sentence, and I believe that you can thoroughly understand the problem of this.

Case 1: If a function has this, but it is not called by a higher level object, then this refers to window. It is important to note that this does not refer to Window in the strict version of JS, but we are not going to discuss the strict version here. You can look it up on the Internet.

Case 2: If a function has this and the function is called by a higher-level object, then this refers to the higher-level object.

Case 3: If a function has this, and it contains multiple objects, even though the function is called by the outermost object, this refers only to the object at the next level above it, as example 3 demonstrates. If you don’t believe me, let’s continue with a few more examples.

var o = {
    a:10.b: {// a:12,
        fn:function(){
            console.log(this.a); //undefined
        }
    }
}
o.b.fn();
Copy the code

Even though object B has no property A, this points to object B, because this only points to the object above it, regardless of whether this has anything in it.

There is another special case, example 4:

var o = {
    a:10.b: {a:12.fn:function(){
            console.log(this.a); //undefined
            console.log(this); //window}}}var j = o.b.fn;
j();
Copy the code

This refers to window, isn’t that confusing? It’s because you didn’t understand one sentence, which is equally important.

This always refers to the object is the last call it, is to see who is calling, when it executes example 4 although function fn were object referenced by b, but in the fn when assigned to the variable j did not perform so eventually points to the window, and this example is not the same as 3, example 3 is directly execute the fn.

Constructor version of this:

function Fn(){
    this.user = "Chaser";
}
var a = new Fn();
console.log(a.user); / / the commitments
Copy the code

The reason why object A can point to the user in function Fn is because the new keyword can change this to point to object A. Why I say a is an object, because using the new keyword is to create an instance of an object. To understand this, think of example 3, Here we use variable a creates an instance of Fn (equivalent to copy a copy of Fn to object inside a), at this time just created, and are not performed, and calls the function object a Fn, so this point to the nature is the object of a, so why there will be a of the object the user, because you have to copy a Fn function to the object a, Using the new keyword is equivalent to making a copy.

Updated a minor issue when this encounters a return

function fn(a)  
{  
    this.user = Chaser;  
    return {};  
}
var a = new fn;  
console.log(a.user); //undefined
Copy the code

Then look at one

function fn()  
{  
    this.user = Chaser;  
    return function(){};
}
var a = new fn;  
console.log(a.user); //undefined
Copy the code

Come again

function fn()  
{  
    this.user = Chaser;  
    return 1;
}
var a = new fn;  
console.log(a.user); / / the commitments
Copy the code
function fn()  
{  
    this.user = Chaser;  
    return undefined;
}
var a = new fn;  
console.log(a.user); / / the commitments
Copy the code

What does that mean?

If the return value is an object, this refers to the returned object. If the return value is not an object, this refers to an instance of the function.

function fn()  
{  
    this.user = Chaser;  
    return undefined;
}
var a = new fn;  
console.log(a); //fn {user: ""}
Copy the code

Another point is that even though null is an object, this still refers to an instance of that function in this case, because NULL is special.

function fn()  
{  
    this.user = Chaser;  
    return null;
}
var a = new fn;  
console.log(a.user); / / the commitments
Copy the code

Related interview questions

let n=1
function A() { this.n = 0; } 
A.prototype.callMe = function () { console.log(this);  }; 
let a = new A(); 
document.addEventListener("click", a.callMe);  //undefined is used to call the document listener without calling the function
document.addEventListener("click".() = > { a.callMe(); });  / / 0
document.addEventListener("click".function () { a.callMe(); });  / / 0
Copy the code

35. What happens from URL input to page presentation?

1. Domain name resolution. Find the IP address by domain name. This can be done from browser caches, operating system caches, host caches, ISP’s DNS servers, and root servers. TCP three-way handshake 3. Send HTTP request 4. The server processes the request and returns HTTP packet 5. Parse HTML to generate DOM tree, parse CSS to generate CSSOM, combine DOM tree and CSSOM to generate Render tree, redraw, rearrange. 6. TCP wave four times

JS garbage collection

Mark clear

The most common method of garbage collection in JS is marked clearly. When a variable is entered into the environment (for example, declaring a variable in a function), the variable is marked as entered into the environment. Logically, you should never free up memory occupied by variables that enter the environment, because they may be used whenever the execution stream enters the corresponding environment. When a variable leaves the environment, it is marked as “out of the environment.”

Variables can be marked in any way. For example, you can flip a particular bit to record when a variable entered the environment, or use a list of variables that entered the environment and a list of variables that left the environment to track which variable changed.

At run time, the garbage collector marks all variables stored in memory (of course, it can be marked in any way). It then removes variables in the environment and variable markers referenced by variables in the environment. Variables tagged after this point are considered to be ready for deletion because they are no longer accessible to variables in the environment. Finally, the garbage collector completes the memory division, destroying the tagged values and reclaiming the memory they occupied.

Reference count (uncommon)

The meaning of reference counting is to keep track of how many times each value is referenced. When a variable is declared and a reference type value is assigned to the variable, the number of references to the value is 1. If the same value is assigned to another variable, the number of references to that value is increased by 1. Conversely, if the variable containing a reference to that value is assigned to another value, the number of references to that value is decreased by 1. When the number of references to the value goes to zero, there is no way to access the value, so it can reclaim its memory. This way, the next time the garbage collector runs, it frees the memory occupied by values with zero references.

Memory leaks occur with reference counting, and here’s why:

function problem() {
var objA = new Object(a);var objB = new Object(a); objA.someOtherObject = objB; objB.anotherObject = objA; }Copy the code
  • Setting undefined will not be garbage collected; setting null will

What is the<! DOCTYPE HTML >?

1 Purpose: Declare the document parsing type (document.compatMode) to avoid browser weird mode.

Document.com patMode: BackCompat: Weird mode. The browser uses its own weird mode to parse rendered pages. CSS1Compat: Standard mode in which browsers parse and render pages using W3C standards.

BackCompat: The standards-compliant mode is disabled. Width of the browser client area is the document. The body. ClientWidth; CSS1Compat: enable the standard compatibility mode. Width of the browser client area is the document. The documentElement. ClientWidth.

This property will be recognized and used by browsers, but if your page doesn’t have a DOCTYPE declaration, then compatMode defaults to BackCompat,

The browser parses the rendered page in its own way, so different styles will appear in different browsers.

If you add that to your page, then it’s the same as turning on standard mode, and the browser has to follow the W3C’s guidelines

Standard parses render pages, so your page will look the same in all browsers.

That’s what delta does.

2 use:

2.1 Use is also very simple, just add “” to the first line of your HTML page

2.2 JSP words, add in <% @page %> next line.

2.3 Case insensitive

37. Box model

IE box model

Width =content Actual width +padding+border

You can use this IE box model with box-sizing property set to border-box

W3C standard box model

The total width of the box model is: margin+padding+border+ defined width

Here WE define width, which is the actual width of the content. Box-sizing’s default property, Content-box, is set to the W3C standard box model;

Compatibility between IE box model and W3C standard box model

How to choose the priority of box model? As mentioned earlier, box-sizing:border-box is rarely used to call the IE box model except in very special cases. Instead, box-sizing: Content-box defaults to the W3C standard box model, which prevents multiple browsers from being incompatible with the same page.

38, cross-domain

What is cross-domain?

Cross-domain refers to requesting resources from a domain name to another domain name. Strictly speaking, as long as the domain name, protocol, and port are different, it is regarded as cross-domain.

What are the specific manifestations of same-origin policy restrictions?

(1) Coikie, LocalStorage, and Index DB cannot be read (2) Dom cannot be obtained (3) AJAX requests cannot be sent

What are the tags that come with cross-domain skills in JS?

JS has two magic tags that come with cross-domain skills from birth, namelyand

Cross-domain solutions

[1] Set document.domain to solve the Cookie problem that cannot read non-homologous web pages

Because the browser checks whether two pages are identical through the document.domain property, two pages can share cookies by setting the same Document.domain (this scheme is only applicable to cross-domain scenarios where the primary domain is the same and the subdomain is different).

[2] Cross-document communication API: window.postmessage ()

Call postMessage to implement the parent window test1.com to send…

It can be used to solve the following problems:

Data transfer between the page and the new window it opens multi-window messaging between the page and the nested iframe messaging above the three scenarios of cross-domain data transfer

// Parent window opens a child window
var openWindow = window.open('http://test2.com'.'title');
 
// The parent window sends a message to the child window (the first parameter represents what was sent, and the second parameter represents the URL of the window that received the message)
openWindow.postMessage('Nice to meet you! '.'http://test2.com');
Copy the code

Call the Message event to listen for messages sent by the other party

// Listen for message messages
window.addEventListener('message'.function (e) {
  console.log(e.source); // e.ource Window to send messages
  console.log(e.origin); // the url to which the message was sent
  console.log(e.data);   // The message sent by e.ata
},false);
Copy the code
【 3 】 the json

JSONP is a common way for servers and clients to communicate across sources. The biggest feature is simple to apply, good compatibility (compatible with low version IE), the disadvantage is only support GET request, do not support POST request.

Core idea: web pages by adding one

Server-side implementation

1) node. Js

router.get('/getinfo'.function(req, res, next) {
  var _callback = req.query.callback;
  var _data = { email: '[email protected]'.name: 'jaxu' };
  if (_callback){
      res.type('text/javascript');
      res.send(_callback + '(' + JSON.stringify(_data) + ') ');
  }
  else{ res.json(_data); }});Copy the code

(2) express implementation

router.get('/getinfo'.function  (req,res,next) {
    var _data = { email: '[email protected]'.name: 'jaxu' };
    res.type('application/json');
    res.jsonp(_data);
});
Copy the code

Client-side implementation

① Native implementation:

// make a request to the server test.com with a callback parameter in the query string that specifies the name of the callback function
 
// Process the data that the server returns from the callback function
<script type="text/javascript">
    function dosomething(res){
        // Process the obtained data
        console.log(res.data)
    }
</script>
<script src="http://test.com/data.php?callback=dosomething"></script>
Copy the code

(2) the jQuery ajax:

$.ajax({
    url: 'http://www.test.com:8080/login'.type: 'get'.dataType: 'jsonp'.// The request is jSONP
    jsonpCallback: "handleCallback".// Custom callback function name
    data: {}});Copy the code

(3) the Vue. Js:

this.$http.jsonp('http://www.domain2.com:8080/login', {
    params: {},
    jsonp: 'handleCallback'
}).then((res) = > {
    console.log(res); 
})
Copy the code

[4] CORS

CORS stands for Cross-Origin Resource Sharing. It is a W3C standard and a fundamental solution for cross-source AJAX requests.

1, common cross-domain request: only need to set access-Control-allow-Origin on the server

2. Cross-domain request with cookie: both the front and back ends need to be set

[Front-end Settings] Determine whether cookies are present based on the xhr.withCredentials field

(1) primary ajax

var xhr = new XMLHttpRequest(); // Ie8/9 must be window.xdomainRequest compatible
 
// Set whether cookies are included in the front end
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); }};Copy the code

(2) the jQuery ajax

$.ajax({
   url: 'http://www.test.com:8080/login'.type: 'get'.data: {},
   xhrFields: {
       withCredentials: true    // Set whether cookies are included in the front end
   },
   crossDomain: true.// The request header contains additional cross-domain information, but does not contain cookies
});
Copy the code

39, requestAnimationFrame and setTimeout() for animation

The animation principles

The image you see is refreshing 60 times a second, so often that you can’t feel it refreshing. The essence of animation is to let the human eye see the visual effect of the change caused by the refresh of the image, and this change should be carried out in a coherent and smooth way. So how do you do that?

The screen with a refresh rate of 60Hz is refreshed every 16.7ms. Before each refresh, we move the position of the image to the left by one pixel, i.e. 1px. This way, each image on the screen will be 1px worse than the previous one, so you’ll see it move; Due to the visual stop effect of our human eyes, the impression of the current position of the image stays in the brain is not lost, and then the image is moved to the next position, so you can see the image in smooth movement, which is the visual effect of animation.

setTimeout

After understanding the above concept, it is not difficult to find that setTimeout is actually to change the position of the image continuously by setting an interval time, so as to achieve the animation effect. However, we will find that animation implemented with seTimeout will stutter and shake on some low-end machines. There are two reasons for this phenomenon:

  • The execution time of setTimeout is not fixed. In Javascript, the setTimeout task is put into an asynchronous queue. Only after the main thread is finished, the task in the queue will be checked to see whether the task needs to be executed. Therefore, the actual execution time of setTimeout is usually later than the set time.
  • The refresh frequency is affected by the screen resolution and screen size, so the refresh frequency may be different for different devices. SetTimeout can only set a fixed interval, which may not be the same as the refresh time of the screen.

requestAnimationFrame

Window. RequestAnimationFrame () this method is used to before the page re-paint, notify the browser call a specified function. This method takes a function as a parameter that will be called before redrawing.

The biggest advantage of requestAnimationFrame over setTimeout is that the system decides when to execute the callback function. To be more specific, if the screen refresh rate is 60Hz, the callback function is executed every 16.7ms, if the refresh rate is 75 hz, the interval becomes 1000/75=13.3ms, in other words, the requestAnimationFrame moves at the pace of the system refresh. It ensures that the callback function is executed only once in each screen refresh interval, thus avoiding frame loss and animation stuttering.

The API call is simple, as follows:

var progress = 0;
// The callback function
function render() {
    progress += 1; // Change the position of the image
    if (progress < 100) {
           // Render recursively before the animation ends
           window.requestAnimationFrame(render); }}// Render first frame
window.requestAnimationFrame(render);
Copy the code

In addition, requestAnimationFrame has the following two advantages:

  • CPU energy saving: When using setTimeout to achieve animation, when the page is hidden or minimized, setTimeout is still performing animation tasks in the background, because the page is not visible or unavailable at this time, refreshing animation is meaningless, it is a complete waste of CPU resources. RequestAnimationFrame is completely different. When the page is not active, the screen refresh task of the page is also suspended, so the requestAnimationFrame that follows the pace of the system will also stop rendering. When the page is active, The animation picks up where it left off, effectively saving CPU overhead.
  • Function throttling: In high frequency events (resize, Scroll, etc.), to prevent multiple function executions in a refresh interval, requestAnimationFrame is used to ensure that functions are executed only once in each refresh interval. This ensures smooth performance and saves function execution costs. It does not make sense if the function is executed more than once in a refresh interval, because the monitor is refreshed every 16.7ms and multiple draws do not show up on the screen.

Browsers that support this method actually expose callback queues as hooks. A hook is a point at which the browser performs the next redraw. The callback queue is a list of modifiable functions that should be called before redrawing. Each call to requestAnimationFrame() pushes a callback function onto the queue, which has no limit on its length. The behavior of this callback queue is not necessarily related to the animation. However, recursively adding callback functions to the queue via requestAnimationFrame() ensures that at most one callback is called per redraw. This is a great throttling tool. This callback queue can be used to throttle code that frequently executes code that affects the look and feel of a page, such as scroll event listeners.

JS on the variable type of five kinds of judgment methods

Method 1: Use Typeof detection

If a variable is number, string, or Boolean

, function, undefined, json, you can use typeof to judge; Other variables are untyped, including NULL.

Typeof does not distinguish array from JSON, because when typeof is used, both array and JSON outputs object

Method 2: Use instance for detection

The instanceof operator is similar to the typeof operator and is used to identify the typeof object being processed. Unlike the Typeof method, the Instanceof method requires the developer to explicitly identify the object as a particular type

Method 3: Use constructor to test

Constructor is originally a property on the prototype object that points to the constructor. However, depending on the order in which the instance object looks for attributes, if there are no instance attributes or methods on the instance object, the constructor attribute is also available

Because undefined and NULL have no constructor attribute, constructor judgments cannot be used

Four: the use of the Object. The prototype. ToString. Call

Object. The prototype. ToString. Call (variable) of the output is a string, the string in an array, the first parameter is the Object, the second parameter is the type of the variable, and that all variables are of type test, we only need to take out the second parameter. Or you can use the Object. The prototype. ToString. Call (arr) = = “Object Array” to detect variable Array arr.