To borrow a famous line from Game of Thrones: “Winter is coming!” Since the beginning of the winter of the Internet, there have been a number of layoffs in keep/ Didi/JINGdong/Tencent/Huawei. Wake up the hair slowly falling off, less of us, it is time to shut up and practice!

This is the front interview foundation, and will be in the form of (spooky spooky) interview answers && ๑, hope you detect and buff your knowledge system!

Interview, we are serious!

JavaScript article

1. JavaScript has several types of values

  • Stack: primitive data type (Undefined, Null, Boolean, Number, String)
  • Heap: Reference data types (objects, arrays, and functions)
  • The difference between the two types is that the storage location is different
    • Primitive data types are directly stored in simple data segments in the stack, occupying small space and fixed size. They are frequently used data, so they are stored in the stack.
    • Reference data type Objects stored in the heap occupy large space, size is not fixed, if stored in the stack, will affect the performance of the program; A reference data type stores a pointer in the stack to the starting address of the entity in the heap. When the interpreter looks for a reference value, it first retrieves its address in the stack and then retrieves the entity from the heap

2. Introduce JavaScript built-in objects

  • Object is the parent Object of all objects in JavaScript
  • Data encapsulation class objects: Object, Array, Boolean, Number, and String
  • Other objects: Function, Arguments, Math, Date, RegExp, Error

3. Null, undefined

  • Undefined means the value does not exist
  • Undefined: a primitive value for “none” or “missing value”, that is, there should be a value here, but it is not defined yet. For example, if a variable is declared but not assigned, it equals undefined
  • Null means that an object is defined and has a value of “null”.
  • Null: is an object (empty object, without any attributes or methods). For example, as a function parameter, the function parameter is not an object. When validating null, be sure to use === because == cannot distinguish null from undefined

4. What is event broker

  • Event Delegation, also known as Event Delegation. Is a common technique for binding events in JavaScript. As the name implies, “event broker” refers to delegating the events that need to be bound to the parent element, allowing the parent element to listen for events. Event broker works by bubbling events from DOM elements.
  • The benefits of using the event broker are:
    • Can improve performance
    • Can save a lot of memory footprint
    • Reduce event registration, such as brokering all TD’s click events on the table

5. The difference between synchronous and asynchronous

  • Synchronization: When the browser requests the server, the user sees the page refresh and sends the request again. After the request is complete, the page is refreshed and the user sees the new content and performs the next operation
  • Asynchronous: The browser requests from the server. The user performs normal operations and the browser requests from the back end. When the request is finished, the page is not refreshed, the new content will also appear, and the user will see the new content

6. The defer and async

  • Defer loads the JS files in parallel, in the order of the Script tags on the page
  • Async loads JS files in parallel and executes them immediately after downloading rather than following the sequence of script labels on the page

7. What are object-oriented programming and procedural programming

  • Process oriented is to analyze the steps needed to solve the problem, and then use functions to implement these steps step by step, use when you can call one by one
  • Object orientation is the decomposition of the transaction that constitutes the problem into various objects. The object is built not to complete a step, but to describe the behavior of something in the whole step of solving the problem. Object orientation is to divide the problem into functions, not steps

8. Object-oriented programming

  • The basic idea is to use objects, classes, inheritance, encapsulation and other basic concepts to program design

  • advantages

    • Easy maintenance using object-oriented design structure, high readability, due to the existence of inheritance, even if the need to change, then maintenance is only in the local module, so maintenance is very convenient and low cost
    • Easy extension
    • The reuse and inheritance of development work are high, and the repetitive workload is reduced
    • Shorten the development cycle

9. What are the functions of callee and Caller in Javascript?

  • Caller returns a reference to a function that calls the current function.
  • The callee is the body of the function function being executed, that is, the specified function object

10. Stages of an event

  • 1: capture stage –> 2: target stage –> 3: bubble stage
  • Document –> target target —-> document
  • Thus, the difference between setting the third parameter of addEventListener to true and false is clear
    • True indicates that the element responds to the event during the “capture phase” of the event, when it is passed from the outside in
    • False indicates that the element responds to the event during its “bubbling phase” (passing from inside out)

11. The closure

  • Closures are functions that can read variables inside other functions
  • A closure is a function that has access to variables in the scope of another function. The most common way to create a closure is to create another function within a function and access local variables of this function through another function. Closures can be used to break through the scope of the scope
  • Closure features:
    • Function nested inside function
    • Inner functions can refer to outer parameters and variables
    • Parameters and variables are not collected by the garbage collection mechanism

Tell me what you know about closures

  • Closures are used primarily to design private methods and variables. The advantage of closures is that they can avoid the pollution of global variables, but the disadvantage is that closures will live in memory, which will increase the memory usage, and improper use will easily cause memory leaks. In JS, functions are closures, and only functions have the concept of scope

  • Closures are useful for reading variables inside functions and for keeping them in memory at all times

  • Closures are also useful for encapsulating the private properties and methods of an object

  • Benefits: Can achieve encapsulation and caching, etc.

  • Disadvantages: Memory consumption, improper use can cause memory overflow problems

  • 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 for web pages and may lead to memory leaks in IE

  • The solution is to remove all unused local variables before exiting the function

12. Explain your understanding of scope chains

  • The function of scope chain is to ensure that the variables and functions that have access to the execution environment are in order. The variables of the scope chain can only be accessed up, and the access of variables to the window object is terminated, while the access of variables down the scope chain is not allowed
  • Simply put, scope is the accessible scope of variables and functions, that is, scope controls the visibility and life cycle of variables and functions

13. JavaScript prototype, prototype chain? What are the characteristics?

  • Every object initializes a property inside it, called prototype, when we access an object’s property
  • If the object doesn’t have the property, it will look for the property in Prototype, which will have its own prototype, and so on and so on
  • Relationship: the instance. The constructor. The prototype = instance. _proto_
  • Features:
  • JavaScript objects are passed by reference, and each new object entity we create does not have a copy of its own prototype. When we modify the stereotype, the objects associated with it inherit the change
  • When we need a property, the Javascript engine looks to see if the property is present in the current Object, and if it isn’t, it looks for the property in its Prototype Object, and so on, until it reaches the Object built-in Object

14. How does Javascript implement inheritance?

  • Tectonic inheritance
  • Prototype inheritance
  • Examples of inheritance
  • Copies of the inheritance
  • The prototype mechanism or the Apply and Call methods are simpler to implement, and a mixture of constructors and prototypes is recommended
    function Parent(){
    this.name = 'wang'; }
    function Child(){
    this.age = 28; }
    Child.prototype = new Parent(); // Parent is inherited from the prototype
    var demo = new Child();
    console.log(demo.age);
    console.log(demo.name); // Get inherited attributes
    
Copy the code

15. What methods do javascript have to define objects

  • Object literals: var obj = {};
  • Constructor: var obj = new Object();
  • Object.create(): var obj = Object.create(Object.prototype);

16. Talk about your understanding of This object

  • This always refers to the direct (not indirect) caller of the function
  • If you have the new keyword, this refers to the object that new came out of
  • In an event, this points to the object that triggered the event. In particular, this in An attachEvent in IE always points to the global object Window

17. What exactly does the new operator do?

  • Creates an empty object, and the this variable references the object and inherits the prototype of the function
  • Properties and methods are added to the object referenced by this
  • The newly created object is referred to by this and implicitly returns this

18. Which operations cause memory leaks?

  • A memory leak is any object that persists after you no longer own or need it
  • Using a string instead of a function as the first argument to setTimeout causes a memory leak
  • Closures are used incorrectly

19. The principle of Ajax

  • The principle of Ajax is simply to add an intermediate layer (the Ajax engine) between the user and the server, make asynchronous requests to the server via XmlHttpRequest objects, get data from the server, and then update the page by manipulating the DOM with javascript. Asynchronize user actions and server responses. One of the most critical steps is getting the request data from the server
  • The Ajax process involves only JavaScript, XMLHttpRequest, and DOM. XMLHttpRequest is the core mechanism of AJA X
    /** 1. Create a connection
    let xhr = null;
    xhr = new XMLHttpRequest()
    /** 2. Connect to server **/
    xhr.open('get', url, true)
    /** 3. Send request **/
    xhr.send(null);
    /** 4
    xhr.onreadystatechange = function(){
    if(xhr.readyState == 4) {if(xhr.status == 200){
    success(xhr.responseText); } else {
    /** false **/fail && fail(xhr.status); }}}Copy the code

What are the pros and cons of Ajax?

  • Advantages:
    • The asynchronous mode improves user experience.
    • Optimized transfer between browser and server to reduce unnecessary data round-trip and reduce bandwidth usage.
    • Ajax runs on the client side, taking over some of the work that would have been done by the server, and reducing the server load under large numbers of users. Ajax allows you to dynamically not refresh (partially refresh)
  • Disadvantages:
    • Security issues AJAX exposes the details of the server interaction.
    • Search engine support is weak. Not easy to debug.

20. How to solve cross-domain problems?

So what is the same origin policy

The Same Origin Policy (SOP) is a convention introduced by Netscape into the browser in 1995. It is the core and most basic security function of the browser. Without the Same Origin policy, the browser is vulnerable to XSS and CSFR attacks. Same-origin means that the protocol, domain name, and port are the same. Even if two different domain names point to the same IP address, they are not same-origin.

The same origin policy restricts the following behaviors:

  • Cookie, LocalStorage, and IndexDB cannot be read
  • DOM and Js objects are not available
  • AJAX requests cannot be sent

Cross-domain solutions are commonly used

  • Cross domains via JSONP
  • Cross-domain Resource Sharing (CORS)
  • Nginx agents cross domains
  • Nodejs middleware proxies cross domains

(PS: limited space, specific usage by baidu)

21. Talk about Event Loop

  • First of all, JS is single-threaded, the main task is to deal with user interaction, and user interaction is nothing more than responding to DOM increase, delete or change, using the form of event queue, an event cycle only one event
  • In response, the script execution is relatively continuous, so there is an event queue, which stores the events to be executed
  • So where does the event queue event get pushed in. That’s what another thread called the event-triggering thread does
  • Its function is mainly in the timing trigger thread, asynchronous HTTP request thread to meet specific conditions of the callback function push to the event queue, waiting for the JS engine idle time to execute, of course, JS engine execution process has priorities, first js engine in an event cycle, will first execute the main task of JS thread, Then it will find whether there is a microtask (promise). If there is, it will preferentially execute the microtask. If not, it will find macroTask (setTimeout, setInterval) for execution

22. What is the relationship between single threading and asynchrony

  • Single thread – Only one thread can do one thing
  • Reason – Avoid DOM rendering conflicts
    • The browser needs to render the DOM
    • JS can modify the DOM structure
    • Browser DOM rendering pauses while JS executes
    • Two JS segments cannot be executed at the same time.
    • Webworkers support multithreading, but do not have DOM access
  • Solution – Asynchronous

23. Have you used jQuery Deferred

With jQuery Deferred:

The summary is as follows:

  • You can’t change the asynchronous and single threaded nature of JS
  • Callback can only be written to eliminate the form
  • It is a syntactic sugar form, but decouples the code
  • A good example: the principle of openness and closure

24. Implementation of asynchronous programming

  • The callback function
    • Advantages: Simple and easy to understand
    • Disadvantages: Poor maintenance, high code coupling
  • Event listening (in time-driven mode, depending on whether an event occurs) :
    • Advantages: Easy to understand, multiple events can be bound, and each event can specify multiple callback functions
    • Disadvantages: Event driven, process is not clear
  • Publish/subscribe (Observer mode)
    • Similar to event monitoring, but you can see how many publishers and subscribers there are by going to message center ʼ
  • Promise object
    • Advantages: Can use then method, chain writing; Can write error callback function;
    • Cons: Relatively difficult to write and understand
  • The Generator function
    • Advantages: data exchange in and out of functions, error handling mechanism
    • Disadvantages: process management is not convenient
  • Async function
    • Benefits: Built-in actuators, better semantics, wider applicability, promises returned, clear structure.
    • Cons: Error handling mechanism

25. Tell me what you know about Promise

  • As defined by Promise/A+, A Promise has four states:
  • Pending: indicates the initial state, which is not fulfilled or rejected.
  • This is a big pity.
  • Rejected: Indicates the failed operation.
  • Settled: Promise has been fulfilled or rejected, and is not pending
  • This is a big pity and rejected
  • The Promise object is used for deferred and asynchronous computations

Promise constructor

  • Construct a Promise. The most basic use is as follows:
  let promise = new Promise(function(resolve, reject) {
    if(...). {// succeed
        resolve(result);
    } else { // fails
        reject(Error(errMessage)); }});Copy the code
  • Promise instances have THEN methods (objects that have THEN methods are often referred to as Thenable). It can be used as follows:
    promise.then(onFulfilled, onRejected)
Copy the code
  • One will be called when fulfilled, and the other will be called when Rejected. The fulfilled parameter is future. OnFulfilled corresponds to resolve, and onRejected corresponds to reject

Talk about your understanding of AMD, CMD

  • CommonJS is the specification for server-side modules, which Is adopted by Node.js. The CommonJS specification loads modules synchronously, meaning that subsequent operations cannot be performed until the modules are loaded. The AMD specification loads modules asynchronously and allows you to specify callback functions
  • The AMD recommended style exposes module objects by returning an object as a module object. The CommonJS style exposes module objects by assigning values to module.exports or exports properties

Es6 modules CommonJS, AMD, CMD

  • In the CommonJS specification, each JavaScript file is a separate module context in which properties created by default are private. That is, variables defined in one file (as well as functions and classes) are private and invisible to other files.
  • CommonJS is a synchronously loaded module that will block in the browser, so it won’t work
  • AMD asynchronous, need to define the callback define mode
  • Es6 A module is an independent file. All variables in the file cannot be obtained externally. If you want the external to be able to read a variable inside the module, you must use the export keyword to export the variable es6 can also export classes, methods, automatically apply strict mode

27. What does Eval do

  • Its function is to parse the corresponding string into JS code and run it
  • Eval should be avoided. It is unsafe and very performance intensive (2 times, once parsed into JS statement, once executed)
  • Var obj =eval(‘(‘+ STR +’)’) var obj =eval(‘(‘+ STR +’)’)

28. “use strict” in javascript code; What does that mean?

  • Use Strict is a strict runtime mode added to ECMAscript 5. This mode makes Javascript run under stricter conditions, makes JS coding more standardized, and eliminates some of the inconsistencies and imrigor of Javascript syntax. Cut down on weird behavior

29. What are the methods of js lazy loading

  • Defer and Async, create the DOM dynamically (most used), and load JS asynchronously on demand

30. Defer and async

  • Defer loads the JS files in parallel, in the order of the Script tags on the page
  • Async loads JS files in parallel and executes them immediately after downloading rather than following the sequence of script labels on the page

31. Progressive enhancement and graceful degradation

  • Progressive enhancement: Build the page for the lower version browser to ensure the most basic functions, and then improve the effect, interaction and additional functions for the advanced browser to achieve a better user experience.
  • Graceful downgrading: Build full functionality from the start and then make it compatible with older browsers

32. Talk about the limitations of strict mode

  • Variables must be declared before being used
  • Function arguments cannot have attributes of the same name; otherwise, an error is reported
  • The with statement cannot be used
  • Disallow this from pointing to a global object

33. How to determine an array from JS

  • Instanceof method
    • The instanceof operator is an attribute used to test whether an object is in its stereotype chain stereotype constructor
    let arr = [];
    arr instanceof Array; // true
Copy the code
  • The constructor method
    • The constructor property returns a reference to the array function that created the object, which returns the corresponding constructor of the object
    let arr = [];
    arr.constructor == Array; //true
Copy the code
  • The simplest way to write this is the way jQuery is using it
    Object.prototype.toString.call(value) == '[object Array]'
    // With this method, you can write a method that returns a data type
    let isType = function (obj) {
    return Object.prototype.toString.call(obj).slice(8.- 1); }   
Copy the code
  • ES5 New method isArray()
    let a = new Array(123);
    let b = new Date(a);console.log(Array.isArray(a)); //true
    console.log(Array.isArray(b)); //false   
Copy the code

34. Differences between Map and forEach

  • ForEach, the most basic method, is traversal and loop. By default, the forEach method takes three parameters: item, index, and Array
  • The map method is the same as forEach, except that it returns a new array, so the callback must have a return value, or undefined if it does not

35. JS array and object traversal way, as well as several ways of comparison

  • The for loop in
  • The for loop
  • forEach
    • The forEach callback has two parameters: value and index
    • ForEach cannot traverse objects. Internet Explorer does not support this method. Firefox and Chrome support
    • ForEach cannot use break, continue to break out of the loop, and return to skip the loop
  • These two methods should be very common and used frequently. In reality, however, both approaches have performance issues
  • In the first approach, for-in needs to analyze each array property, which is very performance expensive. Using an array with a known key is very uneconomical. So try not to use for-in unless you don’t know which properties to work with, such as JSON objects
  • In method 2, the array length is checked every time the loop goes through. Reading properties (array lengths) is slower than reading local variables, especially if the array is full of DOM elements, because each read scans the page for selector-related elements, which is much slower

36. Summary of array deduplication methods

ES6 Set (most commonly used in ES6)

    function unique (arr) {
    return Array.from(new Set(arr)) }
    var arr = [1.2.3.4.5.5.4.3.2.1]
    console.log(unique(arr))
    //[1, 2, 3, 4, 5]
Copy the code

Use for to create a nested for, and then splice to create a new for.

Double loop, outer loop elements, inner loop when comparing values. If the values are the same, delete this value.

    function unique(arr){
        for(var i=0; i<arr.length; i++){
            for(var j=i+1; j<arr.length; j++){
                if(arr[i]==arr[j]){ // The first is the same as the second, the splice method is deleted
                     arr.splice(j,1); j--; }}}return arr; 
    }
Copy the code

Method 3: Use indexOf to remove weights

Create an empty result array, loop through the original array, and check whether the result array has the current element. If they have the same value, skip it. If they do not, push into the array

    function unique(arr) {
        if (!Array.isArray(arr)) {
         console.log('type error! ')
         return
        }
        var array = [];
        for (var i = 0; i < arr.length; i++) {
            if (array .indexOf(arr[i]) === - 1) {
             array .push(arr[i]) 
            } 
        }
         return array; 
    }
Copy the code

Method 4: Use sort()

Use sort() sorting method, and then traverse and compare adjacent elements according to the sorted result

    function unique(arr) {
        if (!Array.isArray(arr)) {
          console.log('type error! ')
          return; 
        }
         arr = arr.sort()
        var arrry= [arr[0]].for (var i = 1; i < arr.length; i++) {
            if(arr[i] ! == arr[i- 1]) { arrry.push(arr[i]); }}return arrry; 
    }
Copy the code

Method five, the use of object attributes are not the same characteristics for deduplication

    function unique(arr) {
        if (!Array.isArray(arr)) {
            console.log('type error! ')
            return
        }
        var arrry= [];
        var obj = {};
        for (var i = 0; i < arr.length; i++) {
            if(! obj[arr[i]]) { arrry.push(arr[i]) obj[arr[i]] =1 } else {
             obj[arr[i]]++
            } 
        }
        return arrry; 
    }
Copy the code

Method 6. Use includes

    function unique(arr) {
        if (!Array.isArray(arr)) {
             console.log('type error! ')
             return
        }
        var array =[];
        for(var i = 0; i < arr.length; i++) {
        if( !array.includes( arr[i]) ) {//includes checks whether the array has a valuearray.push(arr[i]); }}return array
    }
Copy the code

Method 7. Use hasOwnProperty

Use hasOwnProperty to determine whether an object property exists

    function unique(arr) {
        var obj = {};
        return arr.filter(function(item, index, arr){
        return obj.hasOwnProperty(typeof item + item) ? false : (obj[typeof})}Copy the code

Method 8. Use filter

    function unique(arr) {
        return arr.filter(function(item, index, arr) {
        // Current element, the first index in the original array == current index value, otherwise return current element
        return arr.indexOf(item, 0) === index; }); 
    }
Copy the code

Method 9: Use recursion to duplicate

    function unique(arr) {
        var array= arr;
        var len = array.length;
        array.sort(function(a,b){ // It is more convenient to remove the weight after sorting
            return a - b; 
        })
        function loop(index){
            if(index >= 1) {if(array[index] === array[index- 1]){
                 array.splice(index,1); }
                loop(index - 1); // loop recursively, then the array is deduplicated
              } 
            }
        loop(len- 1);
        return array; 
    }
Copy the code

Method 10. Map data structure is used for deduplication

Create an empty Map data structure that iterates through the array to be repealed, storing each element of the array as a key in the Map. Since the Map does not have the same key value, the final result is the result with the duplicate removed

    function arrayNonRepeatfy(arr) {
        let map = new Map(a);let array = new Array(a);// The array is used to return the result
        for (let i = 0; i < arr.length; i++) {
            if(map .has(arr[i])) { // If there is a key value
                map .set(arr[i], true); 
            } else {
                map .set(arr[i], false); // If there is no key valuearray .push(arr[i]); }}return array ; 
    }
Copy the code

Method 11. Use reduce+includes

    function unique(arr){
        return arr.reduce((prev,cur) = > prev.includes(cur) ? prev : [...prev,cu
    }
Copy the code

[…new Set(arr)]

    [...new Set(arr)]
    // The code is so small ---- (actually, it is not strictly a method, just simplified code compared to the first method)
Copy the code

37. Light and dark copy

Shallow copy

  • Object.assign
  • Or expand the operator

Deep copy

  • Parse (json.stringify (object))
  • This approach also has limitations
    • Ignores undefined
    • Non-serializable function
    • Cannot resolve object referenced by loop

38. Anti-shake/throttling

Anti – shake and throttling are different in nature.

  • Anti – shake is to turn multiple executions into the last one
  • Throttling is the process of turning multiple executions into periodic executions

39. What about variable promotion?

  • This is because functions and variables are promoted
  • The usual explanation for promotion is to move the declared code to the top, but there’s nothing wrong with that and it’s easy to understand.
  • But a more accurate explanation would be that there are two phases to generating an execution environment.
    • The first stage is the creation stage. The JS interpreter will find the variables and functions that need to be promoted, and give them space in memory in advance. For functions, the whole function will be stored in memory, and the variable will only be declared and assigned undefined
    • So in the second phase, the code execution phase, we can use it directly ahead of time
  • In promotion, the same function overrides the previous one, and the function takes precedence over the variable promotion

40. let var const

let

  • Allows you to declare a variable, statement, or expression whose scope is limited to the block level
  • The LET binding is not subject to variable promotion, which means that the LET declaration is not promoted to the present
  • This variable is in the “temporary dead zone” from the start of the block until initialization processing

var

  • The scope of declared variables is limited to the context in which they are declared; non-declared variables are always global
  • Since variable declarations (and other declarations) are always processed before any code executes, declaring variables in any bit of code is always equivalent to declaring variables at the beginning of code

const

  • Declare the creation of a read-only reference (pointer) to a value
  • When the value of the base data changes, the corresponding pointer changes, causing const to declare the base data type
  • Changing its value will cause an error, for examplejsconst a = 3 ; a = 5An error will be reported
  • However, if it is a compound type and only one of the values of the compound type is changed, this will still work

41. How can we determine if two objects are equal?

Can be converted to a string to determine

    JSON.stringify(obj1)==JSON.stringify(obj2);//true or false
Copy the code

42. What is the difference between arrow functions and ordinary functions?

  • The this object inside the function is the object at which it is defined, not used
  • Should not be used as a constructor, that is, the new command should not be used, otherwise an error will be thrown
  • You cannot use the Arguments object, which does not exist in the function body. If you do, use the Rest argument instead
  • Yield cannot be used, so arrow functions cannot be used as Generator functions

43. Talk about functional programming as you understand it

  • In short, “functional programming” is a “programming paradigm”, that is, how to write programs
  • It has the following features: closures and higher-order functions, lazy computing, recursion, functions are “first class citizens”, only “expressions”

44. What design patterns have been used?

  • Factory mode:
    • The factory pattern solves the problem of repeated instantiation, but there is also the problem of identifying the problem, because there is no way
    • The main benefit is that you can eliminate coupling between objects by using engineering methods instead of the new keyword
  • Constructor pattern
    • The constructor approach solves both the problem of repeated instantiation and the problem of object identification, which differs from the factory pattern in the following
    • Assign properties and methods directly to this object;

Web related article

1. Understanding of Web standards, usability and accessibility

  • Usability: Whether the product is easy to use, whether the user can complete the task, how efficient it is, and how well the user feels during the process, the quality of the product is viewed from the user’s perspective. Good availability means high product quality, which is the core competitiveness of enterprises
  • Accessibility: Accessibility of Web content to users with disabilities
  • Maintainability: Maintainability consists of two levels. One is to quickly locate and solve system problems. Low cost ensures high Maintainability. The second is whether the code is easy to understand, whether it is easy to modify and enhance features.

2. Describe the whole process from entering the URL to seeing the page, in as much detail as possible

  • First the browser main process takes over, opening a download thread
  • Then it makes an HTTP request (DNS query, IP address, etc.). In the middle, it holds hands three times, waits for the response, and starts to download the response packet
  • The downloaded content is handed over to the Renderer process for management
  • The Renderer process starts parsing the CSS Rule Tree and DOM Tree in parallel, so I usually place the link tag at the top of the page
  • In the process of parsing and drawing, when the browser encounters the link tag or script, IMG and other tags, the browser will download these contents. When it encounters the cache, the cache is used, and the resources that are not applicable to the cache are re-downloaded
  • After the CSS rule tree and DOM Tree are generated, we start to synthesize the Render Tree. At this time, the browser will conduct layout, calculate the position of each node, and then draw
  • After drawing, close the TCP connection with four waves

3. Talk about the browser caching mechanism

There are two types of browser caching mechanisms, one is strong caching and the other is negotiated caching

  • With strong caching, the browser downloads the resource directly on the first request and caches it locally, and uses the cache on the second request
  • For the negotiated cache, the first request cache and store the cache id and time, and the repeated request sends the cache ID and the last cache time to the server. The server verifies the request and uses the cache if it fails

Negotiate cache-related Settings

  • Exprires: the response header of the server that tells the client when the resource will expire on the first request. The drawback of Exprires is that the server time must be strictly synchronized with the client time.
  • Cache-control: max-age: indicates the expiration time of the resource. This eliminates the time synchronization between the client and server
  • If-none-match /ETag: cache identifier, used to identify a cache when comparing caches. The server returns this identifier to the client on the first request. The client compares this identifier with the server on the second request and returns if-none-match to determine whether the cache is a Match
  • Last-modified/If modified – Since: For the first request, the server returns last-Modified indicating the Last modification time of the requested resource. For the second request, the client carries the request header if-modifiedSince indicating the Last modification time of the resource. The server retrieves these two fields for comparison

4. HTTP status code and its meaning

  • 1XX: indicates the information status code
  • 100 Continue Indicates that the server has sent the HTTP header before sending a POST request
  • This message is returned, indicating confirmation, and the specific parameter information is sent
  • 2XX: success status code
  • 200 OK A normal message is displayed
  • 201 Created The request succeeds and the server creates a new resource
  • 202 Accepted the request has been Accepted but not yet processed
  • 3XX: redirection
  • 301 Moved Permanently The page for the Permanently Moved Permanently to the new location.
  • 302 Found Temporary redirect.
  • 303 See Other Temporary redirects and always uses GET to request new URIs.
  • The requested page has Not been Modified since the last request.
  • 4XX: Client error
  • 400 The Bad Request server cannot understand the format of the Request. The client should not use the same capacity to initiate a Request again.
  • 401 Unauthorized The request is not authorized.
  • 403 Forbidden Forbidden access.
  • 404 Not Found The resource how to match the URI was Not Found.
  • 5XX: Server error
  • 500 Internal Server Error Common Server errors.
  • 503 Service Unavailable The server cannot process the request temporarily (possibly due to overload or maintenance).

5. Explain your understanding of browser kernels?

  • It is mainly divided into two parts: layout Engineer or Rendering Engine and JS Engine
  • Rendering engine: Takes the content of a web page (HTML, XML, images, etc.), collates information (such as adding CSS, etc.), calculates how the page should appear, and then outputs it to a monitor or printer. The browser kernel will interpret the syntax of the web page differently, so the rendering effect will be different. All Web browsers, E-mail clients, and other applications that need to edit and display web content require a kernel
  • Javascript engine: parse and execute javascript to achieve the dynamic effect of web pages
  • At the beginning, rendering engines and JS engines were not clearly distinguished, but later JS engines became more and more independent, and the kernel tended to refer only to rendering engines

6. Please describe the difference between cookies, sessionStorage and localStorage.

  • Cookies are data stored (usually encrypted) on a user’s Client Side by a website to identify the user.
  • Cookie data is always carried in the same HTTP request (even if it is not needed) and is passed back and forth between the browser and the server
  • SessionStorage and localStorage do not automatically send data to the server and only store data locally
  • Storage size:
    • Cookie data size cannot exceed 4K
    • SessionStorage and localStorage, while also limited in size, are much larger than cookies, reaching 5M or more
  • Term time:
    • LocalStorage stores persistent data. Data is not lost after the browser is closed unless the data is deleted
    • SessionStorage data is automatically deleted after the current browser window is closed
    • Cookie The cookie set remains valid until the expiration time, even if the window or browser is closed

7. Why is it more efficient to use multiple domain names to store website resources?

  • CDN cache is more convenient
  • Break the browser concurrency limit
  • Save Cookie bandwidth
  • Save the connection number of the main domain name and optimize the page response speed
  • Prevent unnecessary security problems

8. What are redraw and reflow (rearrangement) and how can they be avoided?

  • DOM changes affect the geometry of elements (width and height), the browser recalculates the geometry of elements, and the geometry of other elements
  • Properties and positions will also be affected, and the browser will need to reconstruct the render tree, a process called rearrangement, which will affect the browser
  • The process of redrawing onto the screen is called redrawing. There are several reasons for the rearrangement
    • Add or remove visible DOM elements,
    • Element position, size, content changes,
    • The browser page is initialized
    • Browser window size changes, rearrange must redraw, redraw does not necessarily rearrange

Ways to reduce redrawing and rearrangement:

  • Don’t do DOM queries when layout information changes
  • Change the property once using cssText or className
  • Using the fragments
  • For elements that are rearranged multiple times, such as animations, use absolute positioning out of the document flow so that his changes do not affect other elements

9. Common Web security and defense principles

  • Principles of SQL Injection
    • By inserting SQL commands into Web forms to submit or enter query strings for domain names or page requests, the server can be tricked into executing malicious SQL commands
  • In general, there are the following points
    • Never trust user input. Verify user input by using regular expressions, limiting length, converting single quotes to double “-“, etc. Never use dynamic SQL. Use parameterized SQL or directly use stored procedures for query access
    • Never use database connections with administrator privileges. Use separate, limited database connections for each application
    • Do not store confidential information in plain text. Encrypt or hash out passwords and sensitive information

XSS principle and prevention

  • Xss(Cross-site Scripting) attacks refer to the insertion of malicious HTML tags or javascript code into Web pages. For example, an attacker puts a seemingly secure link in the forum, tricking users into clicking on it and stealing the user’s private information in the cookie; Or an attacker could add a malicious form to a forum, and when a user submits the form, it sends the information to the attacker’s server instead of the trusted site the user thought it was

XSS defense methods

  • First of all, you need to carefully check the length of the user’s input and the variables in the code, and check for “<“, “>”, “; “. , “‘” and other characters to filter; Secondly, any content must be encoded before it is written to the page, to avoid accidentally putting HTML tags out. This layer can block at least half of all XSS attacks

What is the difference between XSS and CSRF?

  • XSS is about capturing information without having to know the code and packets of other users’ pages in advance. CSRF is to complete the specified action on behalf of the user, and need to know the code and packets of other users’ pages. To complete a CSRF attack, the victim must complete two steps in sequence
  • Log in to trusted website A and generate cookies locally
  • Visit dangerous site B without logging out of A

CSRF defense

  • The CSRF method of the server side is very diverse, but the general idea is the same, that is, to increase the pseudo random number in the client page
  • Through the method of verification code

10. WebSocket

Because there is an obvious drawback of HTTP (messages can only be pushed to the server by the client, and the server can not actively push to the client), so if the server has continuous changes, only polling can be used, and polling is too inefficient and not suitable. So WebSocket was invented

Compared to HTTP, it has the following advantages

  • Support two-way communication, more real-time;
  • You can send text or binary files;
  • The protocol identifier is WS and WSS after encryption.
  • Less control overhead. After the connection is created, when the WS client and server exchange data, the packet header controlled by the protocol is small. Without the header, the client-to-client header is only 2 to 10 bytes (depending on the length of the packet), with an additional 4-byte mask for client-to-server. HTTP requires a complete header for each communication.
  • Support for extensions. The WS protocol defines extensions, and users can extend the protocol or implement custom subprotocols. (such as support for custom compression algorithms)
  • No cross-domain problems.

11. Ajax, AXIOS, FETCH, jQuery Ajax

jQuery ajax

The advantages and disadvantages:

  • Itself is for MVC programming, not in line with the current wave of front-end MVVM
  • Based on native XHR development, the architecture of XHR itself is not clear, and there is an alternative to FETCH
  • The whole JQuery project is too big, and it is unreasonable to use Ajax only to introduce the whole JQuery (personalized packaging solution can not enjoy CDN service).

Pros and cons of AXIos:

  • Create an XMLHttpRequest from the browser
  • Making HTTP requests from Node.js supports the Promise API
  • Intercept requests and responses
  • Transform request and response data
  • Cancel the request
  • Automatically convert JSON data
  • The client supports CSRF/XSRF prevention

fetch

The advantages and disadvantages:

  • Fetcht reports errors only for network requests, and considers 400 or 500 requests as successful requests, which need to be encapsulated and processed
  • The FETCH does not carry cookies by default. Configuration items need to be added
  • Fetch does not support abort and timeout control. The actual timeout control using setTimeout and Promise.reject cannot prevent the request process from continuing to run in the background, resulting in a waste of quantity
  • Fetch has no way of natively monitoring the progress of requests, whereas XHR does

12. What performance optimizations did the project make?

  • Reduce the number of HTTP requests
  • Reducing DNS queries
  • Use the CDN
  • Avoid redirection
  • Lazy loading of images
  • Reduce the DOM element count
  • Reduce DOM manipulation
  • Use external JavaScript and CSS
  • Compress JavaScript, CSS, fonts, images, etc
  • To optimize the CSS Sprite
  • Using iconfont
  • Font cutting
  • Multi-domain distribution divides content into different domain names
  • Minimize iframe use
  • Avoid image SRC being empty
  • Place the stylesheet in link
  • Put the JavaScript at the bottom of the page

13. Load balancing

Multiple servers work together, do not let one or a few of them overwork, play the server’s greatest use

  • HTTP redirection Load balancing: The scheduler selects a server based on the policy to respond to the request with 302. The following operations are performed on this server only for the first time. DNS load balancing: The scheduler accesses one of multiple IP servers during domain name resolution (weak monitoring).
  • Reverse proxy load balancing: When a user accesses a unified server, the server schedules the user to access a specific server. The load balancing has a high requirement on the unified server, and its performance depends on the number of servers in the cluster

14. CDN

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

15. Babel principle

ES6, 7 code type -> Babylon to parse -> get AST (abstract syntax tree) -> Plugin to traverse AST tree -> get new AST tree -> pass with babel-generator The AST tree generates ES5 code

16. Talk about your understanding of refactoring

  • Site refactoring: The act of simplifying structure and adding readability while maintaining consistency at the front end of a site without changing external behavior. The idea is to optimize the site without changing the UI, and maintain a consistent UI while extending it
  • For traditional websites refactoring is usually:
    • Table layout changed to DIV+CSS
    • Make the front end of the site compatible with modern browsers (against substandard CSS, such as IE6)
    • Optimization for mobile platforms
    • Optimize for SEO

End of story

Click star if you find this article useful for your training.