Front end development interview questions – Javascript

Time:2021-6-10

js

1. Introduce the basic data types of JS.

(1) Basic type:Boolean、Number、String
(2) Reference type:object、Array、function
(3) Special types:Undefined、Null
(4) ES6 new:Symbol(unique and immutable data type after creation)

How to judge the data type?

Typeof operator
Instanceof operator
Object.prototype.tostring method

typeof 123          // "number"
typeof '123'        // "string"
typeof false        // "boolean"
typeof [1,2,3,4]    // "object"
typeof {name:'john', age:34}    // "object"
typeof null         // "object"
typeof undefined    // "undefined"
typeof function f() {}  // "function"

2. What are the built-in objects in JS?

  • Data encapsulation class objects: object, array, Boolean, number and string
  • Other objects: function, arguments, math, date, regexp, error

3. How many basic rules to write JavaScript?

(1) Do not declare multiple variables on the same line;
(2) Please use = = |== To compare true / false or numeric values;
(3) New array is replaced by literal quantity of object;
(4) Do not use global functions;
(5) The switch statement must have a default branch;
(6) A function should not have a return value sometimes or no return value sometimes;
(7) The for loop must use braces;
(8) If statement must use braces;
(9) Variables in the for in loop should be scoped explicitly with the VaR keyword to avoid scope pollution.

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

definition:

Every object initializes an attribute inside it, that is, prototype. When we access an object’s attribute, if the attribute does not exist inside the object, then it will go to prototype to find the attribute, and the prototype will have its own prototype, so we keep looking for it, that is, the concept of prototype chain.

Relationship: instance.constructor.prototype = instance.proto

characteristic:

  • 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 prototype, the objects associated with it will inherit the change.

  • When we need a property, the JavaScript engine will first check whether the current object has this property, if not,
    It will find out whether the prototype object has this property, and then it will recursively retrieve the object built-in object.

function Func(){}
Func.prototype.name = "Sean";
Func.prototype.getInfo = function() {
    return this.name;
}
var person = new Func();  // Reference var person = object. Create (oldobject);
console.log(person.getInfo());  // " It has func's properties and methods
console.log(Func.prototype);   // Func { name="Sean", getInfo=function()}

5. How many types of values does JavaScript have?, Can you draw their memory map?

(1) Stack: raw data type (undefined, null, Boolean, number, string)
(2) Heap: reference data types (objects, arrays, and functions)

Differences: different storage locations;

  • The original data type is directly stored in a simple data segment in the stack, which occupies a small space and has a fixed size. It belongs to frequently used data, so it is stored in the stack;

  • The object of reference data type stored in heap occupies a large space and its size is not fixed. If stored in the stack, it will affect the performance of the program; The reference data type stores a pointer in the stack to the starting address of the entity in the heap. When the interpreter looks for the reference value, it will first retrieve its address in the stack and obtain the entity from the heap after obtaining the address.

Memory map:

图例

6. How to realize random sorting of arrays?

var arr = [1,2,3,4,5,6,7,8,9,10];

Method 1

function randSort1(arr){
    for(var i = 0,len = arr.length;i < len; i++ ){
        var rand = parseInt(Math.random()*len);
        var temp = arr[rand];
        arr[rand] = arr[i];
        arr[i] = temp;
    }
    return arr;
}

Method 2

function randSort2(arr){
    var mixedArray = [];
    while(arr.length > 0){
        var randomIndex = parseInt(Math.random()*arr.length);
        mixedArray.push(arr[randomIndex]);
        arr.splice(randomIndex, 1);
    }
    return mixedArray;
}

Method 3

arr.sort(function(){
    return Math.random() - 0.5;
})

7. How does JavaScript implement inheritance?

  • Construction inheritance
  • Archetypal inheritance
  • Instance inheritance
  • Copy inheritance

It is easy to implement prototype mechanism or apply and call methods. It is recommended to use the hybrid method of constructor and prototype.

function Parent(){
    this.name = 'wang';
}

function Child(){
    this.age = 28;
}
Child.prototype = new Parent(); // Inherited the parent, through the prototype

var demo = new Child();
console.log(demo.age); // 28
console.log(demo.name); //wang

8. How to create objects with JavaScript?

(1) The way of literal quantity of object

person = {
    firstname:"Mark",
    lastname:"Yun",
    age:25,
    eyecolor:"black"
};

(2) Using function to simulate parameterless constructors

function Person(){}
var person = new Person();// Define a function. If new "instantiation" is used, the function can be regarded as a class
person.name = "Mark";
person.age = "25";
person.work = function(){
    alert(person.name + " hello...");
}
person.work(); //Mark hello...

(3) Function is used to simulate the parameter constructor (this keyword is used to define the context property of construction)

function Pet(name,age,hobby){
    this.name = name;// This scope: current object
    this.age = age;
    this.hobby = hobby;
    this.eat = function(){
        Alert ("my name is" + this. Name + ", I like" + this. Hobby + ", I'm a programmer");
    }
}
Var Maidou = new pet ("McDull", 25, "coding")// Instantiate and create objects
maidou.eat(); //  My name is McDull. I like coding. I'm a programmer

(4) Create (built-in objects) in factory mode

var wcDog = new Object();
Wcdog. Name = Wangcai;
wcDog.age = 3;
wcDog.work = function(){
    Alert ("I am" + wcdog. Name + ", Wang Wang...);
}
wcDog.work(); // I'm Wangcai, wangwangwang

(5) Create it in a prototype way

function Dog(){}
Dog.prototype.name = Wangcai;
Dog.prototype.eat = function(){
    Alert (this. Name + "is a foodie");
}
var wangcai = new Dog();
wangcai.eat(); // Wangcai is a foodie

(6) Create in a mixed way

function Car(name,price){
    this.name = name;
    this.price = price;
}
Car.prototype.sell = function(){
    Alert ("I'm" + this. Name + ", I'm selling" + this. Price + "ten thousand yuan");
}
Var Camry = new car ("Camry", 27);
camry.sell(); // I'm Camry. I'm selling it for 270000 yuan

9. JavaScript scope?

The global function cannot view the internal details of the local function, but the local function can view the upper function details until the global details. When you need to find a property or method from a local function, if the current scope is not found, you will trace back to the upper scope until you find the global function. This organizational form is the scope chain.

10. Talk about the understanding of this object.

  • This always points to the direct (not indirect) caller of the function;
  • In the global environment, this always points to the window object;
console.log(this);  // Point to the window object
  • The function is called directly in the global scope, and this points to window;
function func(){
    console.log(this); // This refers to the window object
}
func();
  • Object function call, which object call points to which object;
var btnOK = document.getElementById("btnOK");
    btnOK.οnclick = function(){
        console.log(this); // This refers to the btnok object
    }
  • If there is a new keyword, this points to the new object;
var Show = function(){
    this.myName = "Mr.Cao"; // This here refers to the obj object
}
var obj = new Show();
  • Use call or apply to change the direction of this
var Go = function(){
    This.address = Shenzhen;
}
var Show = function(){
    console.log(this.address); // Shenzhen
}
var go = new Go();
Show.call(go); // Change this of the show method to point to the go object
  • This object in the body of the arrow function is the object when it is defined, not when it is used.
  • In an event, this points to the object that triggers the event. In particular, this in attachevent in IE always points to the global object window;

11. What does Eval do?

Its function is to parse the corresponding string into JS code and run it;
We should avoid using Eval, which is unsafe and very performance consuming (two times, one parsing into JS statement, one execution).
When converting a JSON string to a JSON object, you can use Eval, VAR obj = Eval (‘(‘ + STR + ‘);

12. What is a window object? What is a document object?

The window object refers to the window opened by the browser.
The document object is a read-only reference of the documentd object (HTML document object) and an attribute of the window object.

What is the difference between null and undefined?

  • null Indicates that an object has no value, that is, the value is empty;
    undefined Indicates that a variable is declared uninitialized (assigned value);

  • Undefined is not a valid JSON, but null is;

  • The type of undefined is undefined;
    The type of null is object;

be careful:When verifying null, be sure to use = =, because = = cannot separate null and undefined

null == undefined  // true
null === undefined // false

14. Write a general event listener function.

markyun.Event = {
    //After loading the page
    readyEvent : function(fn) {
        if (fn == null) {
            fn = document;
        }
        var oldonload = window.onload;
        if (typeof window.onload != 'function') {
            window.onload = fn;
        } else {
            window.onload = function() {
                oldonload();
                fn();
            };
        }
    },
 	//Depending on the ability, use dom0 | dom2 | ie to bind events
 	//Parameters: element of operation, event name, event handler
 	addEvent : function(element, type, handler) {
 		if (element.addEventListener) {
 			//Event type, function to be executed, capture or not
 			element.addEventListener(type, handler, false);
 		} else if (element.attachEvent) {
 			element.attachEvent('on' + type, function() {
 				handler.call(element);
 			});
 		} else {
 			element['on' + type] = handler;
 		}
 	},
 	//Remove event
 	removeEvent : function(element, type, handler) {
 		if (element.removeEventListener) {
 			element.removeEventListener(type, handler, false);
 		} else if (element.datachEvent) {
 			element.detachEvent('on' + type, handler);
 		} else {
 			element['on' + type] = null;
 		}
 	},
 	//Prevent events (mainly event bubbling, because ie does not support event capture)
 	stopPropagation : function(ev) {
 		if (ev.stopPropagation) {
 			ev.stopPropagation();
 		} else {
 			ev.cancelBubble = true;
 		}
 	},
 	//Cancels the default behavior of the event
 	preventDefault : function(event) {
 		if (event.preventDefault) {
 			event.preventDefault();
 		} else {
 			event.returnValue = false;
 		}
 	},
 	//Get event target
 	getTarget : function(event) {
 		return event.target || event.srcElement;
 	},
 	//Get the reference of the event object, get all the information of the event, and ensure that the event can be used at any time;
 	getEvent : function(e) {
 		var ev = e || window.event;
 		if (!ev) {
 			var c = this.getEvent.caller;
 			while (c) {
 				ev = c.arguments[0];
 				if (ev && Event == ev.constructor) {
 					break;
 				}
 				c = c.caller;
 			}
 		}
 		return ev;
 	}
 };

15. What happened? What’s the difference between the event mechanism of IE and Firefox? How to prevent bubbling?

(1) Our operation in the web page (some operations correspond to multiple events). For example, when we click a button, an event will be generated. Is a behavior that can be detected by JavaScript.
(2) Event handling mechanism: ie is event bubbling, and Firefox supports two event models at the same time, that is, capture event and bubbling event;
(3)ev.stopPropagation();( The old IE method ev. Cancelbubble = true;)

16. What is a closure and why use it?

A closure is a function that has the right to access 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 the local variables of the function through another function. Using a closure, you can break through the scope of the scope and pass the variables and methods inside the function to the outside.

The properties of closures are as follows

  • Nested functions within functions
  • Inner functions can refer to outer parameters and variables
  • Parameters and variables are not recycled by the garbage collection mechanism

Application:

//The onclick event of the Li node can correctly pop up the Li Index currently being clicked

     index = 0
     index = 1
     index = 2
     index = 3
var nodes = document.getElementsByTagName("li");
    for(i = 0;i<nodes.length;i+= 1){
        Nodes [i]. Onclick = (function (I) {// without a closure, the value is 4 every time
            return function() {
                console.log(i); //0 1 2 3
            } 
        })(i);
    }
function say667() {
 	var num = 666;
 	var sayNumber = function() {
 		console.log(num);
 	}
 	num++;
 	return sayNumber;
}

var sayNumber = say667();
sayNumber(); //667

After say667() is executed, the internal variables of say667() closure will exist, but the internal variables of closure internal function will not exist, so that the garbage collection mechanism GC of JavaScript will not recover the resources occupied by say667(); Because the execution of the internal function of say667() depends on the variables in say667(); This is the closure effect.

17. “Use strict;” in JavaScript code What do you mean? What’s the difference between using it?

Use strict is a (strict) running mode added by ECMAScript 5, which makes JavaScript run under more strict conditions, makes JS coding more standardized, eliminates some unreasonable and imprecise parts of JavaScript syntax, and reduces some strange behaviors.

  • Bad features supported by default will be disabled. For example, you can’t use with or assign values to global variables in unexpected situations;
  • For the display declaration of global variables, functions must be declared at the top level. Functions are not allowed to be declared in non function code blocks, and arguments.callee is not allowed to be used;
  • To eliminate some unsafe parts of code running, ensure the security of code running, limit the modification of arguments in function, and the behavior of Eval function in strict mode is different from that in non strict mode;
  • Improve the efficiency of compiler and increase the running speed;
  • It paves the way for the standardization of the new version of JavaScript in the future.

18. What does the new operator do?

(1) Create an empty object, and the this variable references the object, while inheriting the prototype of the function.
(2) Properties and methods are added to the object referenced by this.
(3) The newly created object is referenced by this, and finally implicitly returns this.

var obj  = {};
obj.__proto__ = Base.prototype;
Base.call(obj);

19. In JavaScript, there is a function that will never look up the prototype when searching objects during execution. What is this function?

hasOwnProperty

The hasownproperty function in JavaScript returns a Boolean value indicating whether an object has a property with a specified name. This method cannot check whether the attribute exists in the prototype chain of the object; The property must be a member of the object itself.

usage method:

object.hasOwnProperty(proName)
//The parameter object is required. An instance of an object.
//PRONAME is required. The string value of a property name.

If the object has a property with the specified name, the hasownproperty function method in JavaScript returns true; otherwise, it returns false.

What are the ways to delay loading 20. JS?

  • Defer and async
  • Dynamic creation of DOM (most used)
  • Loading JS asynchronously on demand

21. What is Ajax? How to create an Ajax?

Full name of Ajax:Asynchronous Javascript And XML。
Asynchronous transmission + js + xml
The so-called asynchronous, simple explanation is: when sending a request to the server, we don’t have to wait for the result, but we can do other things at the same time. When we have the result, it will carry out the follow-up operation according to the setting. At the same time, the page will not refresh the whole page, which improves the user experience.

(1) To create an XMLHttpRequest object is to create an asynchronous call object
(2) Create a new HTTP request, and specify the HTTP request method, URL, and authentication information
(3) Set functions that respond to changes in the state of HTTP requests
(4) Send HTTP request
(5) Gets the data returned by the asynchronous call
(6) Using JavaScript and DOM to realize local refresh

22. How does Ajax solve the problem of browser caching?

(1) Add anyajax obj. SetRequest header (“if modified since”, “0”) before Ajax sending request;
(2) Add anyajax obj. SetRequest header (“cache control”, “no cache”) before Ajax send request;
(3) Add a random number after the URL: “fresh =” + Math. Random();
(4) Add a timestamp after the URL: “nowtime =” + new date(). Gettime();
(5) If you use jQuery, $. Ajaxsetup ({ cache:false }), so that all Ajax on the page will execute this statement, but there is no need to save the cache record.

23. What’s the difference between synchronous and asynchronous?

  • The concept of synchronization should come from the concept of synchronization in OS: different processes adjust their priorities (by blocking, wakening, etc.) in order to complete a task cooperatively. Synchronization emphasizes the order. Who comes first and who comes later. Asynchronous does not have this order

  • Synchronization: when the browser accesses the server request, the user can see the page refresh and send the request again. When the request is finished, the page refresh and the new content appear, and the user can see the new content and proceed to the next operation.
    Asynchronous: browser access server request, user normal operation, browser back-end request. When the request is finished, the page will not refresh, and the new content will appear, and the user will see the new content.

24. What is the difference between AMD and CMD specifications?

  • For the dependent modules, AMD is executed in advance, and CMD is executed in delay. However, since 2.0, requirejs can also be delayed (depending on the writing method, the processing method is different). As lazy as possible
  • CMD advocates relying on the nearby, amd advocates relying on the front.
// CMD
define(function(require, exports, module) {
    var a = require('./a')
    a.doSomething()
    //Omit 100 lines here
    Var B = require ('. / B') // dependency can be written nearby
    b.doSomething()
    // ...
})

//Amd default recommendation
Define (['. / a', '. / B'], function (a, b) {// dependency must be written at the beginning
    a.doSomething()
    //Omit 100 lines here
    b.doSomething()
    // ...
})

For more information, see another blog postFront end modularization

25. DOM operation – how to add, remove, move, copy, create and find nodes?

(1) Create a new node

Createdocumentfragment() // creates a DOM fragment
Createelement() // creates a specific element
Createtextnode() // creates a text node

(2) Add, remove, replace, insert

Appendchild() // add
Removechild() // remove
Replacechild() // replace
Insertbefore() // insert a new child node before the existing child node

(3) Find

Getelementsbytagname() // by tag name
Getelementsbyname() // through the value of the name attribute of the element (ie has strong fault tolerance, it will get an array, including those whose ID is equal to the value of name)
Getelementbyid() // uniqueness through element ID

26. How to judge whether the current script is running in the browser or node environment?

this === window ? 'browser' : 'node';
//By judging whether the global object is window, if not, the current script does not run in the browser

27. What operations cause memory leaks?

  • A memory leak is any object that still exists after you no longer own or need it.
  • The garbage collector scans objects periodically and counts the number of other objects that reference each object. If the number of references to an object is 0 (no other object has referenced the object), or the only reference to the object is circular, then the memory of the object can be reclaimed.
  • If the first parameter of setTimeout uses a string instead of a function, it will cause a memory leak.
    Closures, console logs, loops (a loop occurs when two objects refer to each other and retain each other)

28. Webpack hot update implementation principle?

(1) During webpack compilation, inject hot update code into the entry that needs hot update (eventsource communication)
(2) After the page is opened for the first time, the server and the client establish a communication channel through eventsource to return the next hash to the front end
(3) The client obtains the hash, which will be used as the hash of the next request to the server for hot-update.js and hot-update.json
(4) After modifying the page code, webpack listens to the file modification and starts compiling. After compiling, it sends the build message to the client
(5) After the hash is obtained by the client, the client constructs the hot-update.js script link and inserts the main document
(6) After hot-update.js is successfully inserted, the hotapi’s createrecord and reload methods are executed to obtain the render method of the Vue component, and then the component is rerendered, so that the UI is updated without refreshing.

ES6 related

1. What is the difference between object. Is() and the original comparison operators “= = =”?

  • When two equal signs are used to judge, type conversion will be performed during comparison;
123 == '123'  // true
null == undefined  // true
1 == true  // true
0 == false  // true
[] == false  // true
  • The third equal sign is equal (strictly judged), and implicit type conversion is not performed during comparison (if the type is different, false will be returned);
123 === '123'  // false
null === undefined  // false
1 === true  // false
0 === false  // false
[] === false  // false

NaN === NaN  // false
+0 === -0  // true
  • Object.is deals with Nan, – 0 and + 0 on the basis of the third grade, which ensures that – 0 and + 0 are no longer the same,
    But object. Is (Nan, Nan) returns true
Object.is(NaN, NaN)  // true
Object.is(-0, +0)  // false
  • Object. Is should be considered to have its special purpose, but not to be more relaxed or strict than other equal contrasts.

2. Set and map data structure

(1)setIt’s like an array, but the values of the members are unique and there are no duplicate values.
(2)WeakSetMembers of can only be objects, not values of other types.

The objects in the weakset are all weak references, that is, the garbage collection mechanism does not consider the reference of the weakset to the object. In other words, if other objects no longer refer to the object, the garbage collection mechanism will automatically reclaim the memory occupied by the object, regardless of the existence of the object in the weakset.
(3)mapValue value correspondence“ The scope of “key” is not limited to strings, and various types of values (including objects) can be used as keys
The key of map is actually bound with the memory address. As long as the memory address is different, it is regarded as two keys. If the key of map is a simple type value (number, string, Boolean value), as long as the two values are strictly equal, map regards it as one key.

(4)weakmapThere are two differences between weakmap and map

  • First, weakmap only accepts objects as key names (except null), and does not accept values of other types as key names.
  • Secondly, the object pointed by the key name of weakmap is not included in the garbage collection mechanism.

Note: weakmap weakly references only the key name, not the key value. The key value is still a normal reference.

3.Proxy

Proxy can be understood as setting up a layer of “interception” in front of the target object, through which external access to the object must be intercepted first. Therefore, it provides a mechanism to filter and rewrite external access. The original meaning of the word “proxy” is proxy. It is used here to “proxy” some operations.

const target = {
    m: function () {
        console.log(this === proxy);
    }
};
const handler = {};
const proxy = new Proxy(target, handler);
target.m() // false
proxy.m()  // true

Although proxy can proxy access to the target object, it is not a transparent proxy of the target object, that is, without any interception, it can not guarantee the consistent behavior with the target object. The main reason is that in the case of proxy proxy, this keyword in the target object will point to proxy proxy.

4.promise

Project is a solution of asynchronous programming. The project object represents an asynchronous operation and has three states: pending, completed and rejected.

characteristic:
(1) The state of the object is not affected by the outside world. Only the result of asynchronous operation can determine the current state. No other operation can change this state.
(2) Once the state changes, it won’t change again. You can get this result at any time. There are only two possibilities to change the state of a project object: from pending to full and from pending to rejected.

limitations:

  • Promise cannot be cancelled. Once it is created, it will be executed immediately and cannot be cancelled halfway.
  • If the callback function is not set, the error thrown by promise will not be reflected to the outside.
  • When it is in the pending state, it is impossible to know which stage (just started or about to finish) it has reached.
  • When an HTTP status code representing an error is received, the promise returned from fetch () will not be marked as reject, even if the HTTP status code of the response is 404 or 500. Instead, it marks the promise state as resolve (but sets the OK property of resolve’s return value to false), and marks it as reject only when the network fails or the request is blocked.

Other issues

1. The difference between get and post

  • Get generates a TCP packet; Post generates two TCP packets. Not all browsers send packets twice in post, but only once in Firefox.
  • Get is harmless when the browser goes back, and post submits the request again.
  • Get is the default method for form submission.
  • Get request parameters will be fully preserved in the browser history, while post parameters will not be preserved.
  • Get is more insecure than post because parameters are directly exposed to URLs, so they cannot be used to pass sensitive information.
  • Do you put the parameters of get in the URL, while post is in the request body.

2. Talk about SEO

For your own web page:

  • TDK, namely title, description and keywords, is added to the page header.
  • Use semantic tags. Such as main, article, header, footer, NAV, aside, section, time, mark, video, audio, etc. W3C compliant: semantic code makes it easy for search engines to understand web pages.
  • Don’t put important content in JS code. Search engines won’t crawl JS code.
  • Improve website performance

Other aspects:

  • Use the HTTPS protocol – secure small green lock.
  • Static URL, short URL, pseudo static.
  • Increase the website chain.
  • Site map, which tells search engines how to crawl your website.
    Take Baidu as an example, take the initiative to submit Baidu included, add robots (in fact, it is a TXT file that tells Baidu engine what it wants to climb and what it can’t climb.)

3. How to refactor the page?

Website reconfiguration: without changing the external behavior, simplify the structure, add readability, and keep consistent behavior in the front of the website.
That is to say, optimize the website without changing the UI, and maintain a consistent UI while expanding.

Traditional website reconstruction

  • The table layout is changed to div + CSS to make the front end of the website compatible with modern browsers (for non-standard CSS, such as IE6)
  • Optimization of mobile platform
  • Optimize for SEO

Deep reconstruction of website

  • Reduce code coupling
  • Keep code resilient
  • Code in strict accordance with the specifications
  • Design extensible API
  • Replace the old framework, language (such as VB)
  • Enhance user experience

Speed optimization

  • Compress JS, CSS, image and other front-end resources (usually solved by the server)
  • Program performance optimization (such as data reading and writing)
  • Using CDN to accelerate resource loading
  • Optimization of JS DOM
  • File cache of HTTP server

4. What is graceful degradation and gradual enhancement?

  • Elegant downgrade: Web sites can work normally in all new browsers. If users use old browsers, the code will downgrade the old version of IE, so that it can experience some form of downgrade in the old browser, but not completely useless.

For example: border shadow

  • Incremental enhancement: start with the basic functions supported by all browsers, gradually add those functions only supported by the new version of browser, and add additional styles and functions to the page that do not affect the basic browser. When the browser supports them, they are automatically rendered and come into play.

For example: Flash upload is used by default, but if the browser supports the file upload function of HTML5, HTML5 is used to achieve a better experience;

5. What front-end performance optimization methods have you used?

(1) Reduce the number of HTTP requests: CSS sprites, JS, CSS source code compression, image size control appropriate; Web gzip, CDN hosting, data caching, image server.
(2) The front-end template JS + data can reduce the bandwidth waste caused by HTML tags. The front-end uses variables to save the Ajax request results. Each time the local variables are operated, there is no request, and the number of requests is reduced
(3) Using innerHTML instead of DOM operation can reduce DOM operation times and optimize JavaScript performance.
(4) When there are many styles to set, set classname instead of directly operating style.
(5) Use less global variables and cache DOM node search results. Reduce IO read operations.
(6) Avoid CSS expression, also known as dynamic properties.
(7) Image preloading, style sheet at the top, script at the bottom, time stamp.
(8) Avoid using table in the main layout of the page. The table will not be displayed until the contents are completely downloaded, which is slower than the div + CSS layout.

There is a unified idea for ordinary websites, which is to optimize the front end as much as possible, reduce database operations, and reduce disk IO. Front end optimization means that, without affecting the function and experience, what can be executed in the browser should not be executed in the server, what can be returned directly in the cache server should not be executed in the application server, what can be directly obtained by the program should not be obtained externally, what can be obtained in the local machine should not be retrieved remotely, and what can be obtained in the memory should not be retrieved from the disk, Some of the cache do not go to the database query. Reducing database operation refers to reducing the number of updates, caching results, reducing the number of queries, allowing your program to complete the operations performed by the database as much as possible (such as join query), reducing disk IO refers to not using the file system as the cache, reducing the number of reading and writing files, etc. Program optimization always needs to optimize the slow part. It is impossible to “optimize” by changing the language.

6. What are the HTTP status codes? What do you mean, respectively?

100 ContinueContinue. Generally, when sending a post request, HTTP has been sent. After the header, the server will return this information to indicate confirmation, and then send the specific parameter information
200 OKNormal return information
201 CreatedThe request succeeded and the server created a new resource
202 AcceptedThe server has accepted the request but has not yet processed it
301 Moved PermanentlyThe requested page has been permanently moved to the new location.
302 FoundTemporary redirection.
303 See OtherTemporary redirection, and always use get to request a new URI.
304 Not ModifiedThe requested page has not been modified since the last request.
400 Bad RequestThe server cannot understand the format of the request, and the client should not try to make the request with the same content again.
401 UnauthorizedThe request is not authorized.
403 ForbiddenNo access.
404 Not FoundCannot find a resource that matches the URI.
500 Internal Server ErrorThe most common server-side error.
503 Service UnavailableThe server cannot handle the request temporarily (possibly due to overload or maintenance).

7. What happens when a page is loaded and displayed from URL input?

Detailed version:

(1) The browser will open a thread to process the request, and analyze the URL to determine that if it is HTTP protocol, it will process it according to the web mode;
(2) Call the corresponding methods in the browser kernel, such as the loadurl method in WebView;
(3) Get the IP address of the web address through DNS resolution, set UA and other information, and send out the second get request;
(4) In the HTTP protocol session, the client sends the header (request header);
(5) Enter the web server on the web server, such as Apache, Tomcat, node. JS and so on;
(6) Enter the deployed back-end applications, such as PHP, Java, JavaScript, python, etc., and find the corresponding request processing;
(7) After processing, the feedback header will be returned. If the browser has visited and there are corresponding resources in the cache, it will be compared with the last modification time of the server. If it is consistent, 304 will be returned;
(8) The browser starts to download the HTML document (response header, status code 200) and use the cache at the same time;
(9) The document tree is established, and the file of MIME type (such as CSS, JS) is specified according to the tag request, and the cookie is set at the same time;
(10) The page starts to render DOM, JS operates DOM according to DOM API, performs event binding, etc., and the page display is completed.

Simple version:

  • The browser gives the DNS domain name resolution according to the requested URL, finds the real IP, and sends the request to the server;
  • The server returns the data after the background processing, and the browser receives the files (HTML, JS, CSS, image, etc.);
  • The browser parses the loaded resources (HTML, JS, CSS, etc.) and establishes the corresponding internal data structure (such as HTML DOM);
  • Load the parsed resource file, render the page, and finish.

Experts can play freely according to their own fields, from URL specification, HTTP protocol, DNS, CDN, database query, to browser streaming parsing, CSS rule construction, layout, paint, onload / domready, JS execution, JS API binding, etc;

Front end frame

If you look at the front-end framework, such as Vue, react, angular, or some frameworks based on this, such as uniapp, elementui, etc., this paper will not make such records for the time being.