I interviewed for the position of front-end development engineer. Since I started my internship in early 2017, I have interviewed more than 50 companies, including 123 interviews, and experienced a total of hundreds of interviews, including Baidu, Tencent, Ali, Didi, netease, Meituan, etc. I also interviewed some small and medium-sized companies for social recruitment.
Summary of the interview encountered problems, hope to help you, this article is very long very long (omit N very long), but after reading, it can deepen the understanding of the front-end basic knowledge, the original link can jump (if it is helpful to you, please help me point a star, regular update) :
I also blog at github.com/fortheallli… Will regularly update some learning experience, also welcome star and fork
First, basic javascript article
1. Error in the parameter length of get request
Myth: We often say that there is a limit to the size of parameters for GET requests and an unlimited number of parameters for POST requests.
In fact, the HTTP protocol never specifies a GET/POST request length limit. The restriction on get request parameters is the source versus the browser or Web server, which limits the length of the URL. To clarify this concept, we must emphasize the following points again:
- The HTTP protocol does not specify the length limit of GET and POST
- The maximum length of GET is displayed because the browser and web server limit the length of the URI
- Different browsers and WEB servers limit the maximum length
- If Internet Explorer is supported, the maximum length is 2083 bytes. If only Chrome is supported, the maximum length is 8182 bytes
2. Add cache differences between GET and POST requests
The differences between POST and GET requests are not detailed.
Add a cache difference between GET and POST:
- Get requests are similar to lookups, where the user retrives the data without having to connect to the database every time, so caching can be used.
- Unlike POST, which generally does modification and deletion work, it must interact with the database, so it cannot use caching. Get requests are therefore suitable for request caching.
3. The closure
In a nutshell, a closure is a function that can read variables inside other functions, or a child function that is called outside the scope of the parent function in which the child function is located is not released.
4. Class creation and inheritance
(1) Class creation (ES5) : add properties and methods to the prototype of the function.
Let’s create an Animal class:
/ / define a Animal function Animal (name) {/ / attribute this. Name = name | | 'Animal'; This.sleep = function(){console.log(this.name + 'sleeping! '); }} function(food) {console.log(this.name + 'eating:' + food); };Copy the code
This generates an Animal class that has methods and properties when it is transformed into an object.
(2) Class inheritance — prototype chain inheritance
Function Cat(){} cat.prototype = new Animal(); Cat.prototype.name = 'cat'; //  Test Code var cat = new Cat(); console.log(cat.name); console.log(cat.eat('fish')); console.log(cat.sleep()); console.log(cat instanceof Animal); //true console.log(cat instanceof Cat); //trueCopy the code
- We can see that new is an empty object that refers to Animal and that Cat.prototype refers to this empty object.
- Features: Based on the prototype chain, both the instance of the parent class and the instance of the child class
- Disadvantages: Multiple inheritance is not possible
(3) Construct inheritance: using the constructor of the parent class to enhance the instance of the child class is equivalent to copying the instance properties of the parent class to the child class (without the stereotype).
function Cat(name){
Animal.call(this);
this.name = name || 'Tom';
}
// Test Code
var cat = new Cat();
console.log(cat.name);
console.log(cat.sleep());
console.log(cat instanceof Animal); // false
console.log(cat instanceof Cat); // true
Copy the code
- Features: Multiple inheritance can be implemented
- Disadvantages: You can only inherit properties and methods from a superclass instance, not from a stereotype.
(4) Instance inheritance and copy inheritance
Instance inheritance: Adds new features to a parent class instance and returns them as a subclass instance
Copy inheritance: Copies attributes and methods on elements of the parent class
The above two practical is not strong, not an example.
(5) Composite inheritance: equivalent to the combination of construction inheritance and prototype chain inheritance. Function reuse is achieved by calling the superclass construct, inheriting the properties of the superclass and retaining the advantages of passing parameters, and then using the superclass instance as a prototype for the subclass
function Cat(name){
Animal.call(this);
this.name = name || 'Tom';
}
Cat.prototype = new Animal();
Cat.prototype.constructor = Cat;
// Test Code
var cat = new Cat();
console.log(cat.name);
console.log(cat.sleep());
console.log(cat instanceof Animal); // true
console.log(cat instanceof Cat); // true
Copy the code
- Features: You can inherit instance properties/methods as well as stereotype properties/methods
- Disadvantages: Superclass constructor is called twice, generating two copies of the instance
(6) Parasitic combination inheritance: By parasitically cutting off the instance properties of the parent class, the instance methods/properties are not initialized twice when the construction of the parent class is called twice
function Cat(name){ Animal.call(this); this.name = name || 'Tom'; } (function(){// create a class with no instance methods var Super = function(){}; Super.prototype = Animal.prototype; Cat.prototype = new Super(); }) (); // Test Code var cat = new Cat(); console.log(cat.name); console.log(cat.sleep()); console.log(cat instanceof Animal); // true console.log(cat instanceof Cat); //trueCopy the code
- A recommendation
5. How do I solve the asynchronous callback hell
Promise, generator, async/await
Talk about the flow of events on the front end
Interactions with javascript in HTML are event-driven, such as the onclick mouse click event, the onScroll page event, and so on. You can add event listeners to the document or elements in the document to order events. To know when these events are invoked, you need to understand the concept of “flow of events.”
What is an event flow: An event flow describes the order in which events are received from the page. The DOM2 level event flow consists of the following stages.
- Event capture phase
- In the target stage
- Event bubble phase
AddEventListener: addEventListener is a new dom2-level event operation that specifies an event handler. This method takes three arguments: the name of the event to be processed, the function that acts as the event handler, and a Boolean value. This last Boolean parameter, if true, means that the event handler is called during the capture phase; If false, the event handler is invoked during the bubbling phase.
IE only supports event bubbling.
7. How do you let events bubble and then capture
In the DOM standard event model, it’s capture before bubble. However, if you want to achieve the effect of bubble first and then capture, for the same event, monitor capture and bubble, respectively corresponding to the corresponding handler function, listen to the capture event, first delay execution, until the bubble event is captured and then execute the capture.
8. Event delegation
-
Brief introduction: Event delegate means that the listener function is not set on the event (direct DOM), but on the parent element, through the event bubble, the parent element can listen to the event triggered on the child element, by judging the event occurrence element DOM type, to make a different response.
-
Example: the most classic is ul and li tags event listening, for example, we add events, event delegate mechanism, not directly on the li tag, but on the ul parent element added.
-
Benefits: Suitable for dynamic element binding, new child elements will also have a listener function, and can also have an event trigger mechanism.
9. Lazy image loading and preloading
-
Preload: Load images in advance and render them directly from the local cache when the user needs to view them.
-
Lazy loading: The main purpose of lazy loading is to reduce the number of requests or delay requests as a front end optimization of the server.
The nature of the two techniques: the two behave in opposite ways, one loading early, the other loading late or even not loading at all. Lazy loading relieves the pressure on the server front end, while preloading increases the pressure on the server front end.
10. Differences between mouseover and mouseenter
-
Mouseover: Events are triggered when the mouse moves over an element or its children, so there is a repetitive, bubbling process. The corresponding removal event is mouseout
-
Mouseenter: An event is raised when the mouse removes the element itself (which does not contain its children), so it does not bubble. The corresponding removal event is mouseleave
What does the new operator in js do
The new operator creates an empty object that refers to the constructor’s prototype and is returned when the constructor executes.
12. Alter this pointer to bind, apply, call
-
The first argument of both functions is the same, indicating the object to be changed. The second argument, apply, is an array, and call, is arg1,arg2… In this form.
-
Changing the this scope with bind returns a new function that does not immediately execute.
13. Various location of js, such as clientHeight scrollHeight, offsetHeight, as well as the scrollTop, offsetTop, what is the difference between clientTop?
-
ClientHeight: represents the height of the visible area, excluding the border and scrollbar
-
OffsetHeight: indicates the height of the visible area, including the border and scrollbar
-
ScrollHeight: represents the height of all areas, including those that are hidden by scrolling.
-
ClientTop: Indicates the thickness of the border border, which is typically 0 if not specified
-
ScrollTop: Height hidden after scroll. gets the height of the object from the top relative to the parent coordinate (the CSS positioned element or body element) specified by the offsetParent property.
14. Implementation of js drag and drop function
-
The first three events are mousedown, mousemove, and mouseup. When the mouse is clicked and pressed, you need a tag to indicate that it has been pressed, and you can execute the specific method in mousemove.
-
ClientX and clientY mark the coordinates of the mouse, respectively the x-coordinate and y-coordinate, and we use offsetX and offsetY to represent the initial coordinates of the element. The example of movement should be:
Coordinates when the mouse moves – coordinates when the mouse presses down.
In other words, the location information is:
Mouse moving coordinate – mouse down coordinate + element initial offetLeft.
-
And the other thing that’s kind of fundamental is that when you’re dragging and you’re absolutely positioning, you’re changing the left and the top and so on for absolute positioning.
Add: It can also be done with HTML5 Drag and drop
Second, advanced javascript article
1. Implement your own bind function
How it works: Apply or call methods.
(1) Initial version
Function.prototype.bind=function(obj,arg){ var arg=Array.prototype.slice.call(arguments,1); var context=this; return function(newArg){ arg=arg.concat(Array.prototype.slice.call(newArg)); return context.apply(obj,arg); }}Copy the code
(2) Consider the prototype chain
Why? When creating a new bind function, you must inherit the original function
Function.prototype.bind=function(obj,arg){ var arg=Array.prototype.slice.call(arguments,1); var context=this; var bound=function(newArg){ arg=arg.concat(Array.prototype.slice.call(newArg)); return context.apply(obj,arg); } var F=function(){} f.prototype =context.prototype; bound.prototype=new F(); return bound; }Copy the code
2. Use setTimeout to implement setInterval
(1) What is the difference between setInterval() and setInterval() simulated by setTimeout()?
Looking first at the pitfalls of setInterval, timers created with setInterval() ensure that the timer code is regularly inserted into the queue. The problem is that if the timer code does not complete execution before the code is added to the queue again, the result is that the timer code will run several times in a row. And there’s no space between them. Fortunately, the javascript engine is smart enough to avoid this problem. Timer code is added to the queue if and only if there is no how code instance for the timer. This ensures that the minimum interval for the timer code to be added to the queue is the specified time.
There are two problems with this rule of repeated timers: 1. Some intervals may be skipped and 2. The code execution time for multiple timers may be smaller than expected.
Here’s an example:
Suppose an onclick event handler uses setInterval() to set a 200ms repeat timer. If the event handler takes a little more than 300ms to complete.
The first timer in this example is added to the queue at 205ms, but does not execute until 300ms has passed. Another copy was added at 405ms. At an interval, 605ms, the first timer code is still executing and there is already an instance of the timer in the queue. The result is that the 605ms timer code is not added to the queue. The result is that the code at 405 executes as soon as the timer code added at 5ms finishes executing.
function say(){
//something
setTimeout(say,200);
}
setTimeout(say,200)
Copy the code
or
setTimeout(function(){ //do something setTimeout(arguments.callee,200); }, 200);Copy the code
3. How to control the js load a picture at a time, after loading the next one
1 (1) method
<script type="text/javascript"> var obj=new Image(); obj.src="http://www.phpernote.com/uploadfiles/editor/201107240502201179.jpg"; Obj.onload =function(){alert(' width = '+obj.width+'; The height of the image is: '+obj.height); document.getElementById("mypic").innnerHTML="<img src='"+this.src+"' />"; } < / script > < div id = "mypic" > onloading... </div>Copy the code
Two (2) method
<script type="text/javascript"> var obj=new Image(); obj.src="http://www.phpernote.com/uploadfiles/editor/201107240502201179.jpg"; Obj.onreadystatechange =function(){if(this.readystate =="complete"){alert(' image width: '+obj.width+'; The height of the image is: '+obj.height); document.getElementById("mypic").innnerHTML="<img src='"+this.src+"' />"; </script> <div id="mypic">onloading...... </div>Copy the code
3. Code execution order
setTimeout(function(){console.log(1)},0); new Promise(function(resolve,reject){ console.log(2); resolve(); }).then(function(){console.log(3) }).then(function(){console.log(4)}); process.nextTick(function(){console.log(5)}); console.log(6); / / output 2,6,5,3,4,1Copy the code
Why is that? See my article on Job Queues in Event loops, starting with Promise, process. NextTick, and setTimeout
4. How to Achieve sleep effects (ES5 or ES6)
(1) the mode of the while loop
function sleep(ms){
var start=Date.now(),expire=start+ms;
while(Date.now()<expire);
console.log('1111');
return;
}
Copy the code
After executing sleep(1000), 1111 is output after 1000ms sleep. The disadvantages of the above circular way are obvious, easy to cause infinite loop.
(2) By promise
function sleep(ms){ var temple=new Promise( (resolve)=>{ console.log(111); setTimeout(resolve,ms) }); Return temple} sleep(500).then(function(){//console. Log (222)}) return temple} sleep(500).then(function(){//consoleCopy the code
(3) Encapsulation via async
function sleep(ms){ return new Promise((resolve)=>setTimeout(resolve,ms)); } async function test(){ var temple=await sleep(1000); console.log(1111) return temple } test(); // Output 1111 after 1000ms delayCopy the code
####(4). Generate
function* sleep(ms){
yield new Promise(function(resolve,reject){
console.log(111);
setTimeout(resolve,ms);
})
}
sleep(500).next().value.then(function(){console.log(2222)})
Copy the code
5. Simply implement a promise
PromiseA + (promiseA+)
PrimiseA + specification
To realize a Promise, see my article:
Implement A Promise that perfectly conforms to the Promise/A+ specification
I don’t usually ask in detail, just write the v1.0 promise in the article above.
6.Function._proto_What is getPrototypeOf?
Gets a prototype of an Object, either as __proto__ in Chrome or as object.getprototypeof in ES6.
So what is function. proto? What object does Function inherit from? Let’s check.
Function.__proto__==Object.prototype //false
Function.__proto__==Function.prototype//true
Copy the code
We find that the prototype of Function is also Function.
We can use the graph to clarify this relationship:
7. Implement the deep clone of all objects in JS (wrapper object, Date object, regular object)
Deep cloning of objects can be easily implemented by recursion, but this approach has the same drawback as ES6 and ES5 implementations. It can only implement deep copying of specific objects (such as arrays and functions). It cannot implement the wrapper object Number, String, Boolean, and Date. Copy the RegExp object.
(1) The methods mentioned above
function deepClone(obj){ var newObj= obj instanceof Array? [] : {}; for(var i in obj){ newObj[i]=typeof obj[i]=='object'? deepClone(obj[i]):obj[i]; } return newObj; }Copy the code
This method can be used to clone general objects and array objects, such as:
Var arr = [1, 2, 3]; var newArr=deepClone(arr); // newArr->[1,2,3] var obj={x:1, y:2} var newObj=deepClone(obj); // newObj={x:1,y:2}Copy the code
It is not possible to clone objects such as Number,String, and Boolean, as well as regular objects such as RegExp and Date, such as:
Var num=new Number(1); typeof num // "object" var newNum=deepClone(num); Var STR =new String("hello"); var STR =new String("hello"); typeof str //"object" var newStr=deepClone(str); //newStr-> {0:'h',1:'e',2:'l',3:'l',4:'o'}; Var bol=new Boolean(true); typeof bol //"object" var newBol=deepClone(bol); // newBol ->{} empty object....Copy the code
(2) the valueof () function
All objects have a valueOf method for: if any original value exists, it defaults to converting the object to the original value representing it. Objects are compound values, and most objects can’t really be represented as a primitive value, so the default valueOf() method simply returns the object itself rather than a primitive value. Arrays, functions, and regular expressions simply inherit from this default method, and calling valueOf() on instances of these types simply returns the object itself.
For raw values or wrapped classes:
function baseClone(base){
return base.valueOf();
}
//Number
var num=new Number(1);
var newNum=baseClone(num);
//newNum->1
//String
var str=new String('hello');
var newStr=baseClone(str);
// newStr->"hello"
//Boolean
var bol=new Boolean(true);
var newBol=baseClone(bol);
//newBol-> true
Copy the code
You can clone a wrapper class using the = sign, but there is no deep cloning.
This is implemented with valueOf, which is more syntactically compliant.
For the Date type:
Because of the valueOf method, the valueOf() method defined by the date class returns an internal representation of it: the number of milliseconds since January 1, 1970. So we can define the method of cloning on the prototype of Date:
Date.prototype.clone=function(){
return new Date(this.valueOf());
}
var date=new Date('2010');
var newDate=date.clone();
// newDate-> Fri Jan 01 2010 08:00:00 GMT+0800
Copy the code
For the regular object RegExp:
RegExp.prototype.clone = function() {
var pattern = this.valueOf();
var flags = '';
flags += pattern.global ? 'g' : '';
flags += pattern.ignoreCase ? 'i' : '';
flags += pattern.multiline ? 'm' : '';
return new RegExp(pattern.source, flags);
};
var reg=new RegExp('/111/');
var newReg=reg.clone();
//newReg-> /\/111\//
Copy the code
8. Simple implementation of Node Events module
Introduction: The observer mode, or subscription mode, defines a one-to-many relationship between objects. Multiple observer objects listen to a topic object at the same time. When an object changes, all objects that depend on it are notified.
The Events module in Node is implemented using the observer mode:
var events=require('events');
var eventEmitter=new events.EventEmitter();
eventEmitter.on('say',function(name){
console.log('Hello',name);
})
eventEmitter.emit('say','Jony yu');
Copy the code
In this case, eventEmitter emits the Say event, receives it through On, and outputs the result. This is the implementation of a subscription mode.
(1) Implement simple Event module emit and on methods
function Events(){ this.on=function(eventName,callBack){ if(! this.handles){ this.handles={}; } if(! this.handles[eventName]){ this.handles[eventName]=[]; } this.handles[eventName].push(callBack); } this.emit=function(eventName,obj){ if(this.handles[eventName]){ for(var i=0; o<this.handles[eventName].length; i++){ this.handles[eventName][i](obj); } } } return this; }Copy the code
With Events defined, we can now start calling:
var events=new Events(); events.on('say',function(name){ console.log('Hello',nama) }); events.emit('say','Jony yu'); // The result is Jony Yu output after calling through emitCopy the code
(2) Each object is independent
Because of the new method, the generated object is different each time, so:
var event1=new Events(); var event2=new Events(); event1.on('say',function(){ console.log('Jony event1'); }); event2.on('say',function(){ console.log('Jony event2'); }) event1.emit('say'); event2.emit('say'); 'Jony event1' 'Jony Event2 ' 'Jony event2'Copy the code
9. This points to an example in the arrow function
var a=11; function test2(){ this.a=22; let b=()=>{console.log(this.a)} b(); } var x=new test2(); / / output 22Copy the code
Definition time binding.
HTTP, HTML, and browser pages
1. The HTTP and HTTPS
SSL encryption for HTTPS is implemented at the transport layer.
(1) Basic concepts of HTTP and HTTPS
HTTP: Hypertext transfer Protocol, the most widely used network protocol on the Internet, is a client and server request and response standard (TCP), used for the transfer of hypertext from the WWW server to the local browser, it can make the browser more efficient, reduce network traffic.
HTTPS: Is an HTTP channel for security purposes. Simply speaking, it is the secure version of HTTP, that is, SSL layer is added to HTTP. The security basis of HTTPS is SSL.
The main function of HTTPS protocol is: to establish a secure channel of information, to ensure the transmission of array, to ensure the authenticity of the website.
(2) What is the difference between HTTP and HTTPS?
The data transmitted through HTTP is unencrypted, that is, plaintext. Netscape sets the SSL protocol to encrypt the data transmitted through HTTP. In short, HTTPS is a network protocol built by HTTP and SSL for encrypted transmission and identity authentication, and is more secure than HTTP. The main differences are as follows:
- Https requires a CA certificate, which is costly.
- HTTP is the hypertext transfer protocol, and information is transmitted in plain text. HTTPS is the SECURE SSL encryption transfer protocol.
- Generally speaking, the HTTP port is 80, and the HTTPS port is 443
- HTTP connections are simple and stateless; HTTPS is a network protocol based on SSL and HTTP for encrypted transmission and identity authentication. It is more secure than HTTP.
(3) The working principle of HTTPS protocol
When the client communicates with the Web server in HTTPS mode, the following steps are performed.
- If the client accesses the server using HTTPS URLS, the Web server must establish SSL links.
- Upon receiving the client’s request, the Web server returns, or transmits, the site’s certificate, which contains the public key, to the client.
- The client and the Web server begin to negotiate the security level, that is, the encryption level, of the SSL link.
- The client browser establishes the session key based on the security level agreed upon by both parties, encrypts the session key using the public key of the website, and sends the session key to the website.
- The Web server decrypts the session key using its private key.
- The Web server encrypts the communication with the client through the session key.
(4) The advantages of HTTPS
- HTTPS is used to authenticate users and servers, ensuring that data is sent to the correct client and server.
- HTTPS is a network protocol based on SSL and HTTP for encrypted transmission and identity authentication. It is more secure than HTTP and prevents data from being stolen or changed during transmission, ensuring data integrity.
- HTTPS is the most secure solution under the current architecture, and while not absolutely secure, it dramatically increases the cost of man-in-the-middle attacks.
- Google tweaked its search engine algorithm in August 2014 and said that “HTTPS encrypted sites will rank higher in search results than their HTTP counterparts.”
(5) Disadvantages of HTTPS protocol
- The HTTPS handshake phase is time-consuming, increasing page load time by 50% and power consumption by 10% to 20%.
- HTTPS caches are not as efficient as HTTP and add data overhead.
- SSL certificates also cost money, and the more powerful certificates cost more.
- An SSL certificate must be bound to an IP address. Multiple domain names cannot be bound to the same IP address. Ipv4 resources cannot support such consumption.
2. TCP three-way handshake
Both the client and the server need to be able to send and receive until they are both available, so a three-way handshake is required.
Simplify the three-way handshake:
The three-way handshake can be simplified as: C initiates a request for connection, S confirms the connection, and C confirms the connection. Let’s take a look at the function of each handshake. C can confirm that S has received the segment sent by it and that it can accept the segment sent by S. The third handshake is as follows: S can confirm that C has received the segment sent by it
3. Differences between TCP and UDP
(1) TCP is connection-oriented, while UDP is connectionless, that is, there is no need to establish a link before sending data.
(2) TCP provides reliable services. That is to say, the data transmitted through the TCP connection, no error, no loss, no repetition, and in order to arrive; UDP does its best to deliver, that is, it does not guarantee reliable delivery. And because TCP is reliable, connection-oriented, and does not lose data, it is suitable for large data volume exchanges.
(3) TCP is byte stream oriented, UDP is packet oriented, and network congestion does not reduce the transmission rate (so there will be packet loss, for real-time applications such as IP phone and video conferencing).
(4) TCP supports only 1-to-1, while UDP supports 1-to-1 and 1-to-many.
(5) TCP header is 20 bytes, while UDP header is only 8 bytes.
(6) TCP is a connection-oriented reliable transmission, while UDP is unreliable.
4. Implementation and application of WebSocket
(1) What is WebSocket?
WebSocket is a protocol in HTML5 that supports persistent connections. HTTP does not support persistent connections. Http1.0 and HTTP1.1 do not support persistent linking. Keep-alive in HTTP1.1 combines multiple HTTP requests into one
(2)WebSocket is what kind of protocol, what specific advantages?
- The life cycle of HTTP is defined by a Request, which is a Response. In Http1.0, this HTTP Request ends. Improved in Http1.1, yes there is a connection: keep-alive, that is, multiple requests can be sent and multiple responses can be received within a single Http connection. However, it must be remembered that in Http, a Request can only have one Response, and this Response is passive, not active.
- WebSocket is based on, or borrows, the Http protocol for part of the handshake, and the handshake phase is the same as Http. Let’s look at an implementation of the WebSocket handshake protocol, which is basically two properties, upgrade and Connection.
The basic request is as follows:
GET /chat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==
Sec-WebSocket-Protocol: chat, superchat
Sec-WebSocket-Version: 13
Origin: http://example.com
Copy the code
The following two attributes are added:
Upgrade:webSocket Connection:Upgrade tells the server to send webSocket sec-Websocket-key: x3JJHMbDL1EzLkh9GBhXDw== Sec-WebSocket-Protocol: chat, superchat Sec-WebSocket-Version: 13Copy the code
5.HTTP request mode, HEAD mode
- Head: This is similar to a GET request, except that there is no specific content in the response returned. The user gets the header
- Options: Allows the client to view the performance of the server, such as how the server supports requests, etc.
6. How to achieve a picture URL directly download after access?
In the return header of the request, the important parameter for browser parsing is the return HTTP header in the OSS API documentation, which determines the user’s download behavior.
In case of download:
1. x-oss-object-type:
Normal
2. x-oss-request-id:
598D5ED34F29D01FE2925F41
3. x-oss-storage-class:
Standard
Copy the code
7. Web Quality (Accessibility)
An easy-to-use website is one that can be used by people with disabilities. Disabled users are those with disabilities or poor health.
Use the Alt attribute:
<img src="person.jpg" alt="this is a person"/>
Copy the code
Sometimes browsers fail to display images. The specific reasons are:
- The user turned off the image display
- The browser is a mini browser that does not support graphical display
- The browser is a voice browser (for blind and visually impaired people). If you use the Alt attribute, the browser can at least display or read a description of the image.
8. How many useful BOM object methods are there?
What is the Bom? A Bom is a browser object. What are the common Bom attributes?
(1) the location object
Location.href — Returns or sets the URL of the current document location.search — returns the query string portion of the URL. For example, www.dreamdu.com/dreamdu.php… Return includes (?) What follows? Id =5&name=dreamdu location.hash — return what follows the URL#, if there is no #, return empty location.host — return the domain name part of the URL, For example www.dreamdu.com location.hostname — returns the primary domain name part of the URL, for example dreamdu.com location.pathname — returns the URL after the domain name. For example www.dreamdu.com/xhtml/ returns/XHTML/location.port — returns the port part of the URL. For example www.dreamdu.com:8080/xhtml/ return 8080 location. Protocol — — return agreement part of the URL. For example www.dreamdu.com:8080/xhtml/ return (/ /) in front of the content of the HTTP: Location.replace () — Sets the URL of the current document and removes the URL location.replace(URL) from the history object’s address list; Location.reload () — Reloads the current page
(2) the history object
History.go () — Forward or back the specified number of pages history.go(num); History.back () — back a page History.forward () — forward a page
(3) the Navigator object
Navigator.useragent — returns a string representation of the userAgent header (that is, a string that includes browser version information, etc.
9.HTML5 drag api
- Dragstart: The body of the event is the drag-dropped element, triggered when the drag-dropped element is started.
- Darg: The body of the event is the dragged element and is triggered when the dragged element is being dropped.
- Dragenter: The body of the event is the target element and is fired when the element is dragged into an element.
- Dragover: The event body is the target element and is triggered when it is dragged and moved within an element.
- Dragleave: The body of the event is the target element and is triggered when the drag and drop element is removed from the target element.
- Drop: The event body is the target element and is fired when the target element fully accepts the element being dragged and dropped.
- Dragend: The body of the event is the element to be dragged and is triggered at the end of the entire drag operation
10. Http2.0
First, a quick note on the differences between HTTP and HTTPS, which is a brief summary of the SSL-based HTTP protocol: Http2.0 is based on the first update since Http1.0 was released in 1999.
- Improved access speed (can be used for resources that take less time to request and access faster than http1.0)
- Allow multiplexing: Multiplexing allows multiple request-response messages to be sent simultaneously over a single HTTP/2 connection. Improved: in HTTP1.1, browser clients have a limited number of requests (connections) for the same domain at the same time, beyond which they will be blocked.
- Binary framing: HTTP2.0 splits all transmissions into smaller pieces of information or frames and encode them in binary
- The first compression
- Server push
11. Add status codes 400 and 401 and 403
(1)400 status code: The request is invalid
Cause:
- The field name and field type of the data submitted by the front end are not consistent with the entity on the back end
- The data that the front end submits to the background should be of JSON string type, but the front end does not convert the object json.stringify to a string.
Solution:
- Compare field names for consistency
- Serialize the obj object through json. stringify
(2)401 Status code: The current request requires user authentication
(3)403 Status code: The server has received the request but is refusing to execute it
12. The reason why the fetch is sent twice
When the FETCH sends a POST request, it always sends a post request twice, the first time the status code is 204, and the second time it succeeds, right?
The simple reason is that when you use fetch’s POST request, the FETCH sends an Options request the first time, asking if the server supports the modified request header, and if it does, the actual request is sent the second time.
13. Differences between Cookie, sessionStorage, and localStorage
Common: Both are stored in the browser and are homologous
-
Cookie: Cookie data is always carried in the same HTTP request (even if it is not needed), that is, cookies are passed back and forth between the browser and the server. SessionStorage and localStorage do not automatically send data to the server and only save the data locally. Cookie data and the concept of path (path), you can limit the cookie belongs to a path, the storage size is very small only about 4K. (Key: can be passed back and forth between browser and server side, small storage capacity, only about 4K)
-
SessionStorage: only in the current browser window closed before the effective, naturally it is not possible to persist, localStorage: always effective, the window or browser closed has been saved, so used as persistent data; A cookie is valid only until the set cookie expiration time, even if the window or browser is closed. (Key: itself is a callback process, close the browser and disappear, session is a callback, if the page is different even if the same page opened twice, it is considered the same callback)
-
LocalStorage: localStorage is shared in all the same source Windows; Cookies are also shared across all the same origin Windows. (key: All same-origin Windows are shared and will not expire, and will remain in effect regardless of whether the window or browser is closed)
A quick note on the role of cookies:
-
Save the user login status. For example, storing the user ID in a cookie so that the user does not need to log in again the next time they visit the page, as many forums and communities now offer. You can also set an expiration time for cookies. When the expiration time expires, cookies will disappear automatically. As a result, the system can often prompt the user for how long to stay logged in: common options are one month, three months, one year, etc.
-
Track user behavior. For example, a weather forecast website can display local weather conditions based on the area selected by the user. If each time you need to choose the location is cumbersome, when the use of cookies will appear very humane, the system can remember the last visit to the region, the next time to open the page, it will automatically display the weather situation of the last user’s area. Because everything is done in the background, such a page is very easy to use as if it were customized for a particular user
-
Customize the page. If the site offers the ability to skin or change the layout, then cookies can be used to record the user’s options, such as background color, resolution, etc. When the user visits next time, the interface style of the last visit can still be saved.
14.web worker
In HTML pages, if the state of the page is not corresponding when the script is executed, the page does not become corresponding until after the script is executed. Web Worker is a JS that runs in the background, independent of other scripts, and does not affect your page performance. And the result is passed back to the main thread via postMessage. In this way, when complex operations are performed, the main thread is not blocked.
How to create a Web Worker:
- Check browser support for Web Workers
- Create web Worker file (JS, return function, etc.)
- Create the Web Worker object
15. Understanding of HTML semantic tags
HTML5 semantic tags mean that the right tags contain the right content, are well structured and easy to read, such as nav for navigation bar, article, header, footer and so on.
16. What is an iframe? What are the disadvantages?
Definition: The iframe element creates an inline frame hint that contains another document: hint text can be placed in between to prompt browsers that do not support iframe
Disadvantages:
- Blocks the onLoad event on the main page
- Search engines can’t read this page, not good for SEO
- The iframe and home page share the connection pool, and browsers have restrictions on the same area, which affects performance.
17. A Doctype? How to distinguish strict mode from promiscuous mode? What do they mean?
The Doctype is declared at the beginning of the document and tells the browser how to render the page. There are two modes, strict mode and promiscuous mode.
- Strict mode typography and JS mode of operation are run to the highest standards supported by the browser.
- Promiscuous mode, backward compatibility, emulation of older browsers, prevent browsers from incompatible pages.
18. How do cookies defend against XSS attacks
XSS (cross-site Scripting) is when an attacker inserts javascript scripts in the HTML returned. To mitigate these attacks, you need to add set-cookie to the HTTP header:
- Httponly – This property prevents XSS, which prevents javascript scripts from accessing cookies.
- Secure – This property tells the browser to send cookies only when the request is HTTPS.
The result should look like this: set-cookie =…..
19. The difference between cookies and sessions
HTTP is a stateless protocol, so the biggest use of cookies is to store sessionids that uniquely identify users
RESTFUL in a word
Urls are used to locate resources and HTTP is used to describe operations
21. Talk about Viewport and mobile layout
Check out my article here:
Comparison of common solutions for responsive layouts (media queries, percentages, REM and VW/VH)
22. Click has 300ms delay on ios, why and how to solve it?
(1) Coarse, disable scaling
<meta name="viewport" content="width=device-width, user-scalable=no">
Copy the code
(2) Using FastClick, its principle is:
When the touchend event is detected, it starts simulating the Click event and blocks the actual event that starts 300 milliseconds later
Fourth, the CSS
1. The CSS box model
Description: A rectangular area used to hold elements on a page. The box model in CSS includes IE box model and standard W3C box model.
Border-sizing: border-box,padding-box,content-box
- Standard box model:
- IE Box model:
The difference between: As can be seen from the figure, the most important difference between the two box models is the scope of width. In the standard box model, width refers to the width of content, while in the IE box model, width refers to the width of content+padding+border. So this makes a difference when calculating the width of the whole box:
Standard box model box width: left and right border+ left and right padding+width IE box model box width: width
CSS3 introduced the box-sizing attribute, box-sizing:content-box; Box-sizing :border-box; box-sizing:border-box
Finally, we mentioned box-sizing:padding-box. This property contains the left and right padding-plus width
It’s also easy to understand and remember that width starts with what it contains.
2. Draw a 0.5px line
-
Use the meta viewport method
-
The border-image mode is used
-
Transform: scale(
3. Differences between the link tag and the import tag
- Link is an HTML tag, and @import is provided by CSS
- While the link is loaded at the same time as the page is loaded, the CSS referenced by @import is loaded after the page is loaded.
- Link is an HTML tag and therefore not compatible, while @import is only recognized by IE5 +.
- Link style has more weight than @import style.
4. The difference between transition and animation
Most of the properties of Animation and Transition are the same. They both change the attribute values of elements over time. The main difference between them is that transition needs to trigger an event to change the attribute values, while Animation does not need to trigger any event to change the attribute values over time. And the transition is 2 frames from…. To, while animation can be frame by frame.
5. The Flex layout
The article links: www.ruanyifeng.com/blog/2015/0… www.ruanyifeng.com/blog/2015/0…
Flex, short for Flexible Box, means “Flexible layout” and is used to provide maximum flexibility for box-shaped models. The traditional solution to the layout, based on the box model, relies on the display + position + float property. It is very inconvenient for those special layouts, for example, vertical center is not easy to implement.
There are simply container attributes and element attributes.
- Flex – direction: the direction of the spindle (i.e., the son of item arrangement method). The box {flex – direction: row | row – reverse | column | column – reverse; }
- Flex – wrap: decided to break the rules. The box {flex – wrap: nowrap | wrap | wrap – reverse; }
- The flex – flow: box {flex – flow: | |. }
- Autocrate-content: specifies the horizontal axis alignment
- Align-items: alignment, vertical axis direction
Attributes of the item (attributes of the element) :
- The order attribute: defines the order in which items are arranged. The smaller the order, the higher the order. The default is 0
- The Flex-grow property: Defines the scale at which the project will be scaled up, even if there is space
- The Flex-shrink property: defines the scale by which an item is shrunk when space is scarce. If flow-shrink is 0 for an item, it is not shrunk
- The Flex-basis property: defines the space occupied by the project before allocating excess space.
- Flex: short for flex-grow, Flex-shrink, and Flex-basis. The default value is 0, 1 auto.
- Align-self: Allows a single item to be aligned differently than other items. It can override the align-items. The default attribute is auto, indicating that the align-items inherit from the parent element
For example, use Flex to implement the Holy Grail layout
6.BFC (block-level formatting context, for clear float, prevent margin overlap, etc.)
The block-level formatting context is a separate render area and has certain layout rules.
- The BFC region does not overlap with the float box
- The BFC is a separate container on the page, and the child elements do not affect the outside
- When calculating the height of the BFC, the float element is also calculated
Those elements generate BFC:
- The root element
- Elements whose float is not None
- Elements whose positions are fixed and Absolute
- Display inline-block, table-cell, table-Caption, Flex, inline-Flex elements
- Overflow is not visible element
7. Vertical centering
(1) margin: auto method
css:
div{
width: 400px;
height: 400px;
position: relative;
border: 1px solid #465468;
}
img{
position: absolute;
margin: auto;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
Copy the code
html:
<div>
<img src="mm.jpg">
</div>
Copy the code
Margin: 0 can achieve separation from the center of the document flow.
(2) the margin negative method
.container{ width: 500px; height: 400px; border: 2px solid #379; position: relative; } .inner{ width: 480px; height: 380px; background-color: #746; position: absolute; top: 50%; left: 50%; margin-top: -190px; Margin-left: -240px; margin-left: -240px; /* half of the width */}Copy the code
Transform: translateX(-50%) and transform: translateY(-50%)
(3) Table-cell (not out of the document flow)
Set display:table-cell to the parent element and vertical-align:middle so that the element is vertically centered.
css:
div{
width: 300px;
height: 300px;
border: 3px solid #555;
display: table-cell;
vertical-align: middle;
text-align: center;
}
img{
vertical-align: middle;
}
Copy the code
(4) using flex
Set the parent element to display:flex and set align-items:center; justify-content:center;
css:
.container{
width: 300px;
height: 200px;
border: 3px solid #546461;
display: -webkit-flex;
display: flex;
-webkit-align-items: center;
align-items: center;
-webkit-justify-content: center;
justify-content: center;
}
.inner{
border: 3px solid #458761;
padding: 20px;
}
Copy the code
8. The difference between JS animation and CSS3 animation
Render threads are divided into the Main thread and the Compositor thread. If the CSS animation only changes transform and opacity, the entire CSS animation is completed in the Compositor trhead (while the JS animation is executed in the Main thread). Note that if transform and opacity are changed, no layout or paint will be displayed. The difference between:
- Function coverage, JS is larger than CSS
- Implementation/reconstruction difficulty is different, CSS3 is simpler than JS, performance optimization direction fixed
- For low version browsers with poor frame rate performance, CSS3 can do natural degradation
- CSS animation has natural event support
- Css3 has compatibility problems
9. Block and row elements
Block elements: occupy a single line and have autofill parent elements, you can set margin and pading as well as height and width line elements: do not occupy a single line, width and height are invalidated, and vertical padding and margin are invalidated.
10. Text ellipses for multi-line elements
display: -webkit-box
-webkit-box-orient:vertical
-web-line-clamp:3
overflow:hidden
Copy the code
11. The visibility = hidden, opacity = 0, display: none
Opacity =0; opacity=0; opacity=0; opacity=0; opacity=0; opacity=0; opacity=0; opacity=0; opacity=0; opacity=0; Display = None does not trigger the event to which the element is bound, hides the element, and changes the layout of the page, as if the element were removed from the page.
12. Double margin overlap (margin folding)
Block elements of multiple adjacent (sibling or parent-child) ordinary streams overlap vertically
The result of folding is:
When two adjacent margins are both positive, the fold results in the larger value between them. When two adjacent margins are both negative, the fold results in a larger value of the absolute value of both. When the margins are one plus one minus, the fold is the sum of the two.