Shan Yue recently resigned naked for four months, New Year’s day around the job search, interviewed several companies, record the following questions
01 How do I enable the selected replication function
In some blogging systems, such as digger’s blog, code can be copied, how is it implemented
Communicate and discuss in Issue or my website: 01 How to implement the function of selected copy
It can generally be implemented using the third-party library clipboard.js, the source is very simple, you can read
There are two main points
- Selected:
Selection API
- Copy:
document.execCommand
Select: Selection API
The Selection takes advantage of the Selection API
The selected code is shown below
const selection = window.getSelection();
const range = document.createRange();
range.selectNodeContents(element);
selection.removeAllRanges();
selection.addRange(range);
selectedText = selection.toString();
Copy the code
The unchecked code is shown below
window.getSelection().removeAllRanges();
Copy the code
It has a third-party library ready to use: select.js
Copy: execCommand
Copying is easy, execCommand
document.exec('copy')
Copy the code
02 As HTTP2 evolves, what traditional approaches to front-end performance optimization can be replaced
Communicate and discuss in Issue or my website: 02 As HTTP2 evolves, which traditional solutions in front-end performance optimization can be replaced
- Sprite figure
- Resource file merge
Since HTTP is a stateless protocol, how does it maintain login state
Communicate and discuss in Issue or my website: 03 Since HTTP is a stateless protocol, how does it stay logged in
The authentication is performed on the server by passing the credentials through cookies or Authorization headers
04 What is the difference between Date and Last-Modified in HTTP response headers, and what should be paid attention to when deploying websites
Communicate and discuss in Issue or my website: 04 What is the difference between Date and Last-Modified in HTTP response headers, and what should be considered when deploying a website
Date
: Indicates the time when a packet is generated on the source server. You can view how long the packet has been cachedLast-Modified
: Time when the resource on the source server was last modified
Lm-factor is related to both of them.
In short, a static resource with no cache-control set will use these two response headers to set the mandatory Cache time (date-lastmodified) * n instead of negotiating the Cache directly. When it comes to CDN, it is more obvious that the interface is not updated after the updated code deployment.
What does the following code output about JSON
More description:
const obj = {
a: 3.b: 4.c: null.d: undefined,
get e () {}
}
console.log(JSON.stringify(obj))
Copy the code
Communicate and discuss in Issue or my website: 05 What does the following code output about JSON
const obj = { a: 3.b: 4.c: null.d: undefined, get e () {} } Copy the code
console.log(JSON.stringify(obj))
Output what?
{"a":3."b":4."c":null}
Copy the code
For undefined, function will ignore json.stringify
06 How do I delete a Cookie
Exchange and discuss in Issue or my website: 06 How to delete a cookie
The cookie can be deleted successfully by changing the expiration time of the cookie to past tense. The specific operation can be completed by operating two fields
max-age
: Maximum number of seconds to expire, set to- 1
You can deleteexpires
: The absolute time to expire, stored tocookies
Is required to passdate.toUTCString()
Process, set the expiration time to delete
Max-age is obviously simpler
// Max-age is set to -1
document.cookie = 'a=3; max-age=-1'
Copy the code
> document.cookie
< ""
> document.cookie = 'a=3'
< "a=3"
> document.cookie
< "a=3"
// Set the max-age of this field to -1
> document.cookie = 'a=3; max-age=-1'
< "a=3; max-age=-1"
// The deletion succeeded
> document.cookie
< ""
Copy the code
Have you ever used CSS variable in 2007? What problems does it solve
Exchange and discuss in Issue or my website: have you ever used CSS variable in 2007 and what problems it solves
@ Cicelychen praise! It is also more flexible than less/ sASS because it is easy to control through JS. It’s a handy way to switch themes.
08 What is the difference between no-cache and No-store
Exchange and discuss in Issue or my website: 08 What is the difference between no-cache and No-store
No-cache and no-store are used as Control caches and are passed by the server to the client through the response header cache-control
no-store
Never store resources on the client side and always fetch resources from the original server
no-cache
Resources can be stored on the client side, but each time you have to go to the server for freshness check to decide whether to fetch the latest resource from the server (200) or read the cache from the client (304), a so-called negotiated cache
When the server resource returns 304, it is associated with those HTTP response headers
In most cases, cache-control: no-cache is required for static resources without hashes in index. HTML or modern build environments to enforce freshness checks on the server each time.
Equivalent to the following response headers
Cache-Control: max-age=0, must-revalidate
Copy the code
Issues related to
- [Q434] Is associated with those HTTP response headers when the server resource returns 304
- 【Q079】 Brief description of HTTP caching mechanism
09 How to Determine whether the current environment is mobile or PC
Communicate and discuss in Issue or my website: 09 How to determine whether the current environment is mobile or PC
UserAgent matches the following re for Android/iPhone
const appleIphone = /iPhone/i;
const appleIpod = /iPod/i;
const appleTablet = /iPad/i;
const androidPhone = /\bAndroid(? :.+)Mobile\b/i; // Match 'Android' AND 'Mobile'
const androidTablet = /Android/i;
Copy the code
Of course, don’t duplicate the wheel, recommend a library: github.com/kaimallea/i…
import isMobile from 'ismobilejs'
const mobile = isMobile()
Copy the code
What is the implementation principle of header compression in HTTP2
Communicate and discuss in Issue or my website: 10 what is the implementation principle of header compression in HTTP2
The HPACK protocol, which is based on Huffman encoding and indexing tables, is taken from the Google developer documentation: http2
Each HTTP transport carries a set of headers that describe the transferred resource and its properties. In HTTP/1.x, this metadata is always in plain text, typically adding 500-800 bytes of overhead per transfer. If HTTP cookies are used, the added overhead can sometimes reach thousands of bytes. (See Measuring and Controlling protocol overhead.) To reduce this overhead and improve performance, HTTP/2 compresses request and response header metadata using the HPACK compression format, which uses two simple but powerful techniques:
- This format reduces the size of the individual transports by supporting the encoding of the header fields of the transports through static Huffman code.
- This format requires both the client and server to maintain and update an index list of previously seen header fields (in other words, it establishes a shared compression context), which is then used as a reference to effectively encode previously transmitted values.
The wireshark can be used to capture and analyze HTTP2 packets.
If you want knowledge, you must take part in the practice of changing reality. If you want to know the taste of a pear, you must change the pear and eat it yourself. If you want to know the organization and properties of atoms, you have to perform physical and chemical experiments and change the atomic condition. If you want to know the theory and methods of revolution, you must take part in it.
The following is a screenshot of the packet capture information
Http2 throughSettings
Frame set header table size for header compression
Http2 with the header compressed, the :method header in the Index table Index is 2
For information about commonly used headers stored in fixed locations in static index tables, see httpwg.org/specs/rfc75…
11 Describe the garbage collection mechanism in Node/V8
Communicate and discuss in Issue or my website: 11 Brief on garbage collection in Node/V8
There are three garbage collection mechanisms in V8
Scavenge
, work in the new generation, thefrom space
Is moved toto space
Mark-Sweep
, flag clear. Some objects in the new generation will be moved to the old generation due to overactivity. At this time, the living objects in the old generation will be marked and the dead objects will be cleanedMark-Compact
, mark finishing.
A link to the
- What are the major garbage collection mechanisms?
- What garbage collection algorithms are used in various programming language implementations
12 How do I delete packages that are not used in the project
Communicate and discuss in Issue or my website: 12 How to delete the package not used in the project
Depcheck can be used to do this
$ npm install depcheck -g
$ depcheck
Unused dependencies
* underscore
Unused devDependencies
* jasmine
Missing dependencies
* lodash
Copy the code
13 Brief CSS Specificity
Communicate and discuss in Issue or my website: 13 Brief CSS Specificity
CSS Specificity refers to the weight of a CSS selector. The following three types of selectors decrease in sequence
id
Selectors, such as#app
class
,attribute
与pseudo-classes
Selectors, such as.header
,[type="radio"]
与:hover
type
Tag selectors and pseudo-element selectors, such ash1
,p
和::before
Where wildcard selector *, combinatorial selector + ~ >, negative pseudo-class selector :not() has no effect on priority
Codepen :not has no effect on the priority of the selector
14 How do I listen to clipboard content in the browser
Communicate and discuss in Issue or my website: 14 How do I listen to clipboard content in the browser
The Clipboard API allows you to access Clipboard contents, but you need to obtain clipboard-read permission. Here is the code for reading Clipboard contents:
// Can read the clipboard permission
// result.state == "granted" || result.state == "prompt"
const result = await navigator.permissions.query({ name: "clipboard-read" })
// Get the clipboard contents
const text = await navigator.clipboard.readText()
Copy the code
Note: This method does not take effect in DevTools
Related questions: [Q019] How to implement the function of selected copy
15 How can I avoid CDN caching mobile Pages for the PC
Exchange and discuss in Issue or my website: 15 How to avoid CDN caching mobile pages for PC
This problem does not occur if PC and mobile are the same code. This problem occurs when PC and mobile are two sets of code, but share the same domain name.
Use nginx configuration as follows, according to UA to determine whether mobile terminal, and follow different logic (determine whether mobile terminal is prone to problems)
Location / {// default PC root /usr/local/website/web; # UA, access to the mobile end if ($http_user_agent ~ * "(Android | webOS | the | the | BlackBerry)") {root/usr/local/website/mobile; } index index.html index.htm; }Copy the code
Solutions typically use the Vary response header to control the CDN’s caching of different request headers.
Here you can useVary: User-Agent
, indicating that if the User-Agent is different, the request is re-initiated instead of reading the page from the cache
Vary: User-Agent
Copy the code
Of course, if there are too many user-agents, there will be too many cache invalidation.
Short answer
Vary: user-Agent is used to cache by UA.
Vary: User-Agent
Copy the code
However, it is best not to do this. If there are two sets of codes for PC and mobile, it is recommended to use two domain names for the following reasons
nginx
Determine whether the mobile terminal is prone to error- Not cache friendly
16 This section describes requestIdleCallback and its application scenarios
16. Briefly introduce requestIdleCallback and usage scenarios
RequestIdleCallback maintains a queue that will be executed during browser idle time. It belongs to the Background Tasks API, which you can emulate using setTimeout
window.requestIdleCallback = window.requestIdleCallback || function(handler) {
let startTime = Date.now();
return setTimeout(function() {
handler({
didTimeout: false.timeRemaining: function() {
return Math.max(0.50.0 - (Date.now() - startTime)); }}); },1);
}
Copy the code
The above implementation is too complex and detailed, you can also do a simple simulation implementation like SWR, see github.com/vercel/swr/…
const rIC = window['requestIdleCallback'] | | (f= > setTimeout(f, 1))
Copy the code
Note the following when performing tasks in rIC:
- Perform recalculation instead of emergency tasks
- Idle callback execution time should be less than 50ms, preferably less
- Do not manipulate the DOM in idle callbacks, because it takes advantage of the idle time between rebeats and redraws. Remanipulating the DOM will cause rebeats and redraws
React time sharding is implemented based on rIC. However, due to rIC’s compatibility and 50ms fluency problems, React has a home-made implementation called Scheduler
In use-SWr, rIC is also used to improve the performance of resource revalidate
reference
The two introductions on MDN and W3C are highly recommended
- Background Tasks API – MDN
- requestIdleCallback – W3C
17 How to implement inheritance in JS
Exchange and discuss in Issue or my website: 17 How to implement inheritance in JS
There are two ways to implement inheritance
class
/extends
class Animal {
constructor (name) {
this.name = name
}
hello () {
console.log('hello')}}class Dog extends Animal {
constructor (name, say) {
super(name)
this.say = say
}
}
Copy the code
function
/new
function Animal (name) {
this.name = name
}
Animal.prototype.hello = () = > {
console.log('hello')}function Dog (name, say) {
// 01 Inherit attributes
Animal.call(this, name)
this.say = say
}
// 02 Completes inheritance by concatenating the prototype chain
Dog.prototype = Object.create(Animal.prototype)
// add constructor
Dog.prototype.constructor = Dog
// Reflect.defineProperty(Dog.prototype, "constructor", {
// value: Dog,
// Enumerable: false, // not enumerable
// writable: true
// })
Copy the code
18 Format the certificate in HTTPS
Exchange and discuss in Issue or my website: 18 what is the formatting information of certificates in HTTPS
During TLS handshake, the server needs to provide a certificate to the client.509 is the standard certificate format.
Here’s what github’s certificate looks like on a Mac:
- The serial number
- Subject Name
- Issuer Name
- The electronic signature
- Signature algorithm
- The public key
- extension
A link to the
- What Is an X.509 Certificate?
How to optimize website performance in TLS layer
Communicate and discuss in Issue or my website: 19 How to optimize website performance in TLS layer
- OSCP Stapling
- The TLS 1.3
Implement a function to parse the queryString URL
More description: Examples, such as
const url = 'https://shanyue.tech? a=3&b=4&c=5' // Get qs as follows const qs = { a: 3.b: 4.c: 5 } Copy the code
[Q440] implements a function to encode the QueryString of the URL
Communicate and discuss in Issue or my website: 20 Implement a function to parse the QueryString of the URL
Regarding queryString parsing in routing, both front-end and back-end development use this feature all the time, even though almost no one parses it manually. Let’s implement a simple and crude analytic function
- How to parse QS using re
- How to escape Chinese characters correctly
- How do I handle arrays correctly
- How to handle complex nested objects
How to implement complex nested objects, too many boundary conditions, strongly recommend a NPM library QS
The following use cases are summarized to check the correctness of the analytic function
/ / {}
'https://shanyue.tech'
// {a: ''}
'https://shanyue.tech? a'
// {name: 'mountain '}
'https://shanyue.tech? name=%E5%B1%B1%E6%9C%88'
// {name: 'mountain ', a: 3}
'https://shanyue.tech? name=%E5%B1%B1%E6%9C%88&a=3'
// {name: ' ', a: [3, 4]}
'https://shanyue.tech? name=%E5%B1%B1%E6%9C%88&a=3&a=4'
// {name: 'mountain ', a: 3}
'https://shanyue.tech? name=%E5%B1%B1%E6%9C%88&a=3#hash'
// {name: '1+1=2'}
'https://shanyue.tech? name=1%2B1%3D2'
Copy the code
Instead of using the browser DOM feature API, the code is shown below, with details in the comments
function parse(url) {
// What do you mean? Before the # character is qs, use /\? ([^ /? # :] +) #? / re to extract
// Use the re to parse queryString from the URL
// Use Optional Chain to avoid null errors
const queryString = url.match(/ \? ([^ /? # :] +) #? /)? .1]
if(! queryString) {return {} }
queryObj = queryString.split('&').reduce((params, block) = > {
If no value is assigned, it defaults to an empty string
const [_k, _v = ' '] = block.split('=')
// four, through decodeURIComponent to escape characters, remember not to appear in the beginning, in case? Tag = 2 b1 test&title = 1% % 3 d2 is wrong
const k = decodeURIComponent(_k)
const v = decodeURIComponent(_v)
if(params[k] ! = =undefined) {
// If the key appears multiple times, set it to array
params[k] = [].concat(params[k], v)
} else {
params[k] = v
}
return params
}, {})
return queryObj
}
Copy the code
If you introduce a browser feature API, the problem will be much easier to solve. There are two apis involved, which will not be expanded here
new URL(url)
new URLSearchParams(paramsString)
21 How to implement an array shuffle function shuffle
Exchange and discuss in Issue or my website: 21 How to implement an array shuffle function shuffle
const shuffle = (list) = > list.sort((x, y) = > Math.random() - 0.5)
Copy the code
Day to ask
Welcome to pay attention to personal website: Internet big factory interview a daily question, including big factory promotion opportunities, interview and a number of interview questions, study five minutes a day, a year into the big factory.
- Dachang front end test questions
- Big push
blog
Welcome to GitHub mountain and moon blog: shfshanyue/blog, which contains my problems encountered in practical work, thinking about business and learning in the direction of the full stack
- Chances are you don’t need a server
- Front-end engineering series
- Node advanced series