Different from the ordinary interview text, from the question to thoroughly understand the principle of practice, so that you can directly in the interview scene. Ps: DO I have a pussy?

Please do not pay to go to the toilet when watching, so as to avoid hemorrhoids – with the heart micro doctor

Dog egg came to the interview site, the interviewer is a fierce tattoo man, the heart is full of timidity, feel Alexander ~~

Interviewer: So, tell me what optimization you think will give you the best quality improvement in your project?

Dog egg: H T T P resources

The interviewer sneers 😏 the young man began to dig a hole

Interviewer: How to optimize?

Dog egg: two directions, reduce the number of requests or resource size

Interviewer: Man: What are they?


Reduce resource volume

gzip

Gzip uses the LZ77 algorithm and Huffman encoding to compress files, and the more repetitive the file, the more space it can compress

How do I check whether Gzip is enabled to compress code?

— Open the control panel and go to NetWork. Right-click Response Headers and select Content-Encoding

Content-encoding: Content Encoding formats gzip and Deflate

1. First, the browser sends the request with its accept-encoding list

2. After receiving the request, the server selects one to encode the response information, and uses content-Encoding to specify the Encoding information selected by the server

3. The browser decompresses the response text according to Content-Encoding.

Copy the code

case


We can see how much smaller the file is with gzip enabled (the smaller the file is, the less noticeable)

To optimize the

Nginx open

Some highlights are listed

gzip on;

gzip_min_length 1k; // Do not compress the critical value, greater than 1K compression, generally do not change

gzip_comp_level 2// Compression level, 1-10, the higher the number, the finer the compression, the longer the compression time

gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png; // The type of file to compress

gzip_disable "MSIE [1-6]\.";// Ie compatibility is not good so discard

Copy the code

Webpack open

Compression -webpack-plugin this plug-in can provide functionality and benefits

const CompressionWebpackPlugin = require('compression-webpack-plugin');

plugins.push(

    new CompressionWebpackPlugin({

        asset'[path].gz[query]'.// Target file name

        algorithm: 'gzip'.// Use gzip compression

        test: new RegExp(

            '\\.(js|css)$' // Compress js and CSS

        ),

        threshold10240.// resource files will be compressed if they are larger than 10240B or 10kB

        minRatio: 0.8 // It is compressed when the minimum compression ratio reaches 0.8

    })

);

Copy the code

Interviewer: What does webpack’s Gzip have to do with Nginx’s?

1.nginxThere is no opengzipCompression.webpackPack out.gzDocuments are not needed

2.nginxOpen thegzip.nginxLooks for static resources that are already compressedgzipCompress the file, if not, compress it (consumecpuBut less perception.)

3.nginxopengzipCompression.webpackPack out.gzFiles are found, pre-compressed and used directly, reducednginxCompression loss of

Copy the code

in-depth

Interviewer: How is gzip compressed?

To this step are not ordinary people, I will briefly: use"Sliding window"Method to find every string in the file with the minimum matching length

, the duplicate content is stored in the dictionary table with a hash value and replaced on the matching string to achieve compression, so the more duplicate the file can be compressed more space.

Copy the code

Source file control

There are a number of solutions, such as webpack, which uses splitchunks and loads to break up large AppJS into smaller packages. Webpack optimization will be covered in the next issue.

The picture

Webp is an image file format that provides both lossless and lossless compression (reversible compression). Lossless webP is 26% smaller than PNG files, and lossless WebP images are 25% to 34% smaller than JPEG images with equivalent quality specifications.

The only problem may be compatibility!! The compatibility of all evils I am against you

Another solution, in ancient times we also use direct lossy compression images to reduce the volume zhainanba.net/go/13513

Http2 — Header compression

HTTP request and response are composed of three parts: status line, request/response header, and message body. In general, the body of the message is either gzip compressed or itself transmitted as a compressed binary (such as image, audio), but the status line and header are not compressed and are transmitted as plain text. There are always multiple HTTP requests within a website, and headers take up a lot of bytes. In particular, cookies, headers sometimes even exceed the size of the main body.


Open up any url and see if this is a graph where basically most of the HEADERS content for HTTP is the same,

in-depth

Interviewer: How does head compression work?

Frame’s sentiments will be covered later.


Similar to the form of an object key-value pair:

1, a fully matched header key-value pair. For example :method:GET, can be directly represented by a character

2HTTP /)2The static dictionary in:



    method    GET

    path    /index.html

    scheme    https

    cookie



At the same time, the browser can tell the server to add cookie: XXXXXXX to the dynamic dictionary so that the entire subsequent key-value pair can be represented by a single character.

Similarly, servers can update each other's dynamic dictionaries. Note that the dynamic dictionary context is relevant to the need for each HTTP/2The connection maintains different dictionaries.



The static dictionary can be used in the first request. For the content that does not exist in the static and dynamic dictionary, Huffman coding can also be used to reduce the volume.

HTTP/2A static Huffman code table is used, which needs to be built into the client and server.

Copy the code

Reducing resource requests

DNS

What is DNS?

For example, to visit Baidu.com, the domain name can be resolved into AN IP address. The DNS system can only find out its IP address. The MAIN reason is that IP is too difficult for us users to remember, so DNS resolves the domain name to IP address.

During DNS query, the browser waits and the white screen lasts a long time. If there are too many DNS queries, the performance deteriorates. Therefore, DNS cache is required.

in-depth

Interviewer: How does DNS work?

1. Check whether the browser has cache

2. Check whether the operating system cacheshostsfile

3. Check whether the router has a cache

4. Whether the DNS server has cache: root domain server (.)-> Top-level domain name server (com)-> Master domain name server (baidu.com)

Copy the code

To optimize the

<link rel="dns-prefetch" href="//baidu.com">

Copy the code

It is important to note that while using DNS Prefetch can speed up page parsing, it should not be abused, as some developers have pointed out that disabling DNS Prefetch could save 10 billion DNS queries per month.

To disable implicit DNS Prefetch:

<meta http-equiv="x-dns-prefetch-control" content="off">

Copy the code

The HTTP protocol

The main thing is optimizations for HTTP2,

Why is core binary layering core mainly because some of the optimizations for HTTP2 are implemented based on binary layering

A Frame is the smallest unit of transmission in HTTP2 communication. All frames begin with a fixed nine-octet header, followed by a payload of variable length


Split an HTTP message into DATA frames and HEADERS frames as shown above.

multiplexing

When a TCP connection is established, http2 will reuse the TCP request and split it into multiple streams. Slow requests or first sent requests will not block the return of other requests.

The Header frame must precede the Data frame, which depends on the information parsing of the Header frame

in-depth

Interviewer: What is the difference between http2 multiplexing and keep-alive for http1.x?

At first glance, it looks like they're being reusedTCPYes, but they're totally different.



http1.x:

It follows the first in, first out, the server can only respond to requests in order, so if the previous request does not respond to the end of the grainy queue head blocking, causing delays, while maintaining unnecessary connections will affect server performance, at the same time browser restrictionshttpThe maximum number of concurrent requests.

http2:

Multiple requests can be sent simultaneously (in no particular order) and responded sequentially, solving 1.xSome of the problems.

Copy the code

Service delivery

A server can actively push other resources while sending the page HTML, rather than waiting for the browser to parse to the appropriate location and then respond to the request. The client can abort the push by sending an RST_STREAM frame.

case

The server can actively push JS and CSS files to the client without having to send these requests while the client parses the HTML.

Implementation:

  location / {

    root   /usr/share/nginx/html;

    index  index.html index.htm;

    http2_push /Home.css;     / / push the CSS

    http2_push /Home.png;     // Push image

  }

Copy the code

in-depth

Interviewer: Why hasn’t your company enabled HTTP2 yet??

Big boob brother front nginx with a finish, have you considered my back end brother’s feelings?

  1. Nginx 1.1 and later (nginx does an elegant downgrade, and uses 1.1 if not supported)
  2. First I need HTTPS support
  3. Jetty 9.3 and later
  4. Apache 2.4.17 and later

What if you want to upgrade but the server does not support it?

Here's the plan:

client->nginx http2. 0    

nginx->service http11.

Copy the code

The cache

This is one of the worst questions to ask, and if you don’t know, it’s time to reexamine yourself

If the HTTP code is 304, the cache is hit.

Cache flow chart

Strong caching: Expires, cache-control

More tough, hit the cache rules directly cache

Interviewer: The difference between Expires and Cache-Control

Expires, such as: Thu,01 Dec 1994 16:00:00 GMT

Indicates the specific expiration time of the resource, after which a request must be sent to the server,

However, if the server resources are not synchronized with the PC's local time, the cache update policy may be inconsistent, for example, the user changes the time himself.



Cache-control, which specifies the maximum amount of time (in seconds) from the time of the request to allow the retrieved response to be reused.

For example, Max - age =60Represents available in the following60Second caching and reuse of responses.



If both Expires Expires is overridden by the max-age of cache-control

Copy the code

in-depth

Interviewer: What are the properties of cache-control

No-cache: Data cannot be cached and the server is re-accessed for each request. If max-age exists, the server is not accessed during the cache

No-store: not only cache, but also temporary storage (that is, the resource cannot be temporarily stored in the temporary folder).

Private (default): Cache only in the browser. The server is accessed only on the first request. If max-age exists, the server is not accessed during cache

Public: can be cached by any cache, such as browser, server, proxy server, etc

Max-age: indicates the relative expiration time of the cache in seconds

S-maxage: only used for shared caches, such as CDN caches (s- > share). The difference with max-age is that max-age is used for ordinary caching with relative expiration times

S-maxage is used for proxy caching. Max-age and Expires are overridden if s-maxage is presentCopy the code

Negotiated caching occurs when the resource cache exceeds the strong cache limit.

Negotiated cache: last-Modified, ETag

As the name implies, you can negotiate caching with the server

There are two pairs of negotiation caches:

 If-Modified-since: Last-Modifed



 If-None-Match: Etag

Copy the code

Last-Modified

Browser request → Server returns last-Modified field → Browser requests again → Browser request header carries if-Modified-since: server returns Last Modified time → Browser request header carries if-Modified-since: server returns Last Modified time → Browser request header carries if-Modified-since: Server returns Last Modified time → The server takes if-modified-since to compare with the last Modified time of the resource in the server → equal to return 304 read cache, less than the last Modified time repeat the first access

ETag Browser request → Server returns ETagd field (unique identifier generated based on the contents of the current file) → Browser requests again → Browser request header carries if-none-match: unique identifier → If the server uses if-none-match to compare the current ETag of the resource in the server → equal, 304 is returned to the cache. If the resource is not equal, a new request is required

in-depth

Interviewer: Difference between Last-Modified and ETag

Last-modified cannot be updated in the case of second-level changes. That is, if a file changes more than once in a second, the changes cannot be detected and may result in the file being cached.



However, last-Modified is easier to calculate than Etag, because it has been mentioned above that the time point and the difficulty of calculating the uniquely identified hash code are different, so last-Modified is superior in performance



The server priority ETag> last-Modified.

Copy the code

review

Do you understand the cache properties in there?

LocalStorage and sessionStorage

Browser-level local storage is stored in the user’s local browser and can be viewed by the Application storage in the browser

Cookie (storage = 5M, cookie4K), also corresponding to a domain name,

Note that if you are using localStorage to permanently store a large amount of content, use code to periodically release it

Only the client does not participate in server communication, so the security problem of Cookie is avoided in identity verification.

    const Interviewer = { name:"Plum Dog eggs".position:"FE"};

    / / set

    sessionStorage.setItem("Interviewer".JSON.stringify(Interviewer));

    localStorage.setItem("Interviewer".JSON.stringify(Interviewer));

    / / read

    const localviewer = sessionStorage.getItem("Interviewer");

    const sessionviewer = localStorage.getItem("Interviewer");

Copy the code

in-depth

Interviewer: localStorage and sessionStorage differences, and application scenarios

LocalStorage: the browser is still closed

1. The store token

2. Resource storage

3. Habitual storage



SessionStorage: The browser closes and disappears

1. The current data store saves HTTP requests

2. Flip pages to store data

Copy the code

cdn


As shown in the figure, CDN is what we call the proximity principle.

in-depth

Interviewer: Tell me about CDN

Based on the intelligent DNS resolution of the user's IP address comprehensive reference rules and numerical indicators, the user is scheduled to the fastestCacheThe server



People speaking! : Select the nearest site for request, saving the consumption of the source site (back source)

Copy the code

The maximum number of download requests for the same domain name by the browser at the same time is limited. Multiple domain names can be used to store different static resources to increase the number of parallel downloads of resources during page loading and shorten the loading time of page resources. Usually, putting images in a dedicated CDN domain name is a solution.

CDN can also do cache, prevent attacks and so on. For details, it is better to refer to the CDN scheme provided by major companies in the industry

The picture

Interviewer: What are the options for reducing image resource requests, as opposed to reducing image size?

1. The Sprite

2. Transfer the image to Base64

Copy the code

Sprite figure

It is an image that combines multiple images together and uses the way of background positioning to obtain what one wants. It is often used in icon collection, so that HTTP requests of multiple ICONS can be reduced through one image.

Background-position is a very difficult solution to calculate, but I don’t want to be so troublesome

If HTTP2 is used, this problem can be solved

base64

Base64 is A representation based on the selection of 64 printable characters “A-z, A-z, 0-9, +, /” to represent binary data. Base64 originally came because binary files contain many characters that cannot be displayed and printed. Base64 can convert binary strings and display them. For example, when you open exe, JPG and PDF files with Notepad, there will be binary data that cannot be displayed.

The latest browsers come with two methods for base64 encoding and decoding

Atob (Base64 to ASCII) and BTOA (Base64 to ASCII)

in-depth

Interviewer: How to transcode base64 and its application scenarios?

Base64 transcoding converts 4 bytes into 3 bytes. Read in four six bits (with or), move left six bits each time, and then move right three times, eight bits each time, and you’re back.

Scene:

  1. Simple data encoding
  2. Error free transmission of content
  3. Email (SMTP protocol)
  4. The image is base64 encoded

Interviewer: What is the purpose of transferring pictures to base64?

For small images such as icon, base64 encoding can reduce the network request of one image. For larger images, base64 encoding will mix with HTML, increasing the size of THE HTML page, but increasing the size of the downloaded page. Therefore, urL-loader provides the function of setting the limit

Base64 encoded images cannot be cached like normal images, but writing in CSS allows the browser to cache CSS files

How do you do that?

1. window.btoa(str)

2. canvas.toDataURL();

3. var reader = new FileReader();

   imgUrlBase64 =reader.readAsDataURL(file);

4. webpack:url-loader 

Copy the code

Asynchronous loading

Defer, Async, module

<script async src="index1.js"></script>

<script defer src="index2.js"></script>

<script type="module" src="index3.js"></script>

Copy the code

DOMContentLoaded:

When the initial HTML document is fully loaded and parsed, the DOMContentLoaded event is fired, and the DOM tree has been generated.

But other external resources, such as style files, images, fonts, etc., are not loaded properly.

Copy the code

Defer executes before the DOMContentLoaded event and executes the scripts in the order they were declared (queued). Ps. Depending on the browser, it may not always be executed before the DOMContentLoaded event, so it is best to include only a deferred script

Async executes as soon as it is downloaded, thus interrupting the rendering, so async is not guaranteed to be sequential.

The Module/Nomodule browser supports ES6 code directly, as well as defer (the default) and Async.

Due to browser compatibility problems, it is not recommended to use all modules to optimize file size (reduce transcoding volume).

Above review:

Dom render download performs three colors corresponding to the line below

in-depth

Interviewer: Tell me about the usage scenarios of defer and Async

It's not hard to guess,deferIs definitely more suitable for multiple JS interdependent and have the execution order of the scenario, in most cases, including major scaffolding is also the defaultdefer(Bottom of page), the business code is best.



Async is better suited for hosting SDKS or other unrelated third-party resources.

Copy the code

Interactive program

  • Lazy loading of images
  • The waterfall flow
  • The rolling load

Asynchronous loading scheme thousands of thousands, thousands of changes are inseparable from its case, here will not expand into details, pay attention to throttling and shaking. Here’s a good API to recommend

Intersection Observer See MDN

preload

preload

<link rel="preload" href="style.css" as="style">

Copy the code

This directive can be used in the link tag, as above, to pre-request the resources needed for the current page.

MDN’s description of preload:


If the tag contains the AS attribute, it indicates the highest priority; if it does not, it is demoted to normal preloading

prefetch

The browser retrieves the resources that preFETCH is set to when idle (not when requested) and stores them in the browser’s cache. When a static resource containing PreFETCH is used, the content is loaded from the cache.

in-depth

Interviewer: Similarities and differences between Preload and Prefetch

In common

Asynchronous preloading

When a resource containing preload or Prefetch is found during a page load, it is transferred from the network stack to the HTTP cache and into the renderer's memory cache.



If the resource contains a cache field (for example, a validcache- control andmax-age), which will be stored inHTTPAvailable in the cache for current and future requests that trigger it;

If no cache is set, it is cached in the in-memory cache and remains unchanged until it is used.

Copy the code

The difference between

preload: Direct request

Prefetch: idle time request

Copy the code

Note the necessity of using these attributes. If they are not used, this is an additional waste of bandwidth, which is negative optimization, especially on mobile terminals

Safe direction

This is an interview question you have to bring up

https

Pain points

HTTP is stateless plaintext transmission, whereas HTTPS provides encryption transmission and identity authentication, which is relatively unbreakable

With HTTP difference


In the figure, we see a layer of SSL\TLS added to TCP to HTTP

  • The HTTP port number is 80 and the HTTPS port number is 443
  • HTTPS is charged, mainly because of the ca certificate authority in the middle

Combine the following problem to see the picture to think, help you understand thoroughly

Noun explanation

Symmetric key: The same key can be used to encrypt and decrypt information

Asymmetric key: one private key and one public key. Only the corresponding public key can decrypt the data encrypted with the private key, and only the corresponding private key can decrypt the data encrypted with the public key.

Copy the code

in-depth

Interviewer: Why ca?

The listening

HTTP is plaintext, whereas HTTPS listens for ciphertext data.



Anti-man-in-the-middle attack

Hijacked communication between the server and the client, disguised as client and server camouflage, and then tampered with the attack.



How does ** CA organization solve **

The certificate is issued by a third-party authority, and the public key of the CA root certificate exists in the browser of the client

During the TCP handshake, the server returns the wrapped CA certificate.

The CA certificate package contains the plaintext of the public key of the applicant, the organization information and personal information of the applicant, the ca information of the issuing institution, the validity time, and the serial number of the certificate, and the encrypted signature of the CA private key to the information abstract.

Most importantly, they carry company information, domain names,

Server information, so even if the hijacking can not be perfectly forged.

Copy the code

Interviewer: Why does the client generate a random symmetric key instead of an asymmetric key after ca authentication?

HTTPSSymmetric encryption is used in the encryption of content transmission, and asymmetric encryption only works in the certificate verification phase.



The efficiency of asymmetric encryption is very low, and the efficiency of asymmetric encryption is unacceptable in the application scenarios of HTTP, where there are a lot of end-to-end interactions.



In THE HTTPS scenario, only the server saves the private key. A pair of public and private keys can only be used for one-way encryption and decryption. Therefore, the content transmission encryption in HTTPS is symmetric rather than asymmetric.

Copy the code

Basic attack

Know you learn not to move, I will simplify, can see other articles in detail!

XSS (Cross Site Script)

XSS is about injecting someone else’s malicious scripts into your pages

  • Reflective: the server returns the script and the client executes it (directly injected through the URL argument)
  • Storage type: background storage, front-end display (post or comment input content, storage into the database after reading injection)
  • DOM type: Based on DOM (traffic hijacking, DNS hijacking, modify page script structure)

Defense scheme

  • Http-only: After the HttpOnly attribute is set in the cookie, the JS script cannot read the cookie information.
  • Filtering and translation: nuggets, for example, have comment functions but our alert(1) is not implemented, is it? The front end is sensitive text processing, .innerhtml,.outerhtml, document.write(), eval(), setTimeout(), setInterval(), V-html (VUE), dangerouslySetInnerHTML(react) and so on The Pre tag is also going to run the code directly and have to pay absolute attention to the contents of the string.

An XSS NPM package is recommended

in-depth

What SQL injection is

Isn't that back-end knowledge? A lot of students will subconsciously lose their nerve



Don't worry, it's just XSS, but with SQL commands,

To trick the server into executing malicious SQL commands.

Copy the code

Cross Site Request Forgery (CSRF) /XSRF

Saving cost and complexity, this attack method is less than XSS

Identity theft to forge, do some malicious operations

  • Falsifying identity: intercepting cookies, obtaining user information, stealing accounts, illegal transactions and transfers
  • Cross-site: tags such as IMG cross domain GET request, POST automatic form submission, malicious link jump, and use login state and cookie to complete cross-site forgery request

Defense scheme

The most important is the third party impersonation, so to do a good job of identity authentication precautions

  • Certification means: verification Referer, image verification, live authentication, voice prompts, face recognition bara Bara…
  • Token: Page insert token (hidden in a tag, usually in form input, not cookie), JWT (JSON Web Token)

Remember, wait, wait, wait

Interviewer: Not bad. I’ll report to the security brigade tomorrow

Dog egg:??

Send resume to hit my mailbox [email protected]


Close to next year’s job-hopping period and a step closer, now do not grasp when to grasp, pay attention to me, micro health insurance you on the way to find a job medicine to cure a disease, all the way up

Quality four consecutive, like, attention, forward, comment

Learn more, pay attention to technology public number: IHAP technology black hole!!