1. Semantic HTML tags
Do the right thing with the right label
Semantic advantages:
- It is easy for users to read and provides a clear structure when styles are lost
- SEO, search engines based on tags to determine the context and the weight of each keyword, conducive to browser crawlers
- Easy for other devices to parse, such as blind readers render web pages according to semantics
- Easy for team development and maintenance, more readable
2. Cross domain
2.1 Same Origin Policy
Source: The protocol, domain name, and port are the same. Same-origin policy: The same-origin policy restricts the following behaviors:
- Cookie, LocalStorage, and IndexDB cannot be read
- DOM and Js objects are not available
- AJAX requests cannot be sent with the same Origin policy, which is the core and most basic security function of the browser. Without the same origin policy, the browser is vulnerable to XSS and CSFR attacks.
2.2 Cross-domain Solution
- JSONP
Dynamically create script, and then request a reference url to achieve cross-domain communication. Cons: Can only get one request, can’t send a specific header, can’t send a body, rarely used nowadays.
- postMessage
PostMessage is an API in HTML5 XMLHttpRequest Level 2, and is one of the few window properties that can operate across domains. It can be used to solve the following problems:
A.) page and the new window it opens
B.) Message passing between multiple Windows
C.) page with nested iframe message passing
D.) cross-domain data transfer in the above three scenarios
Usage: The postMessage(data, Origin) method takes two arguments
- Cross-domain Resource Sharing (CORS)
Access-control-allow-origin can be set only in the server request header. The front end does not need to be set. To request with cookies, both the front and back ends need to be set.
3. cookies & localStorage & sessionStorage&indexedDB
Benefits of Web Storage:
- The API interface is easy to use
- Supports event notification, which can send notifications of data updates to listeners
- Reduce network traffic: Once data is stored locally, it avoids further requests to the server, thus reducing unnecessary data requests and data passing back and forth between the browser and the server unnecessarily.
- Fast display of data: Performance is good, reading data from the local is much faster than getting data from the server over the network, local data can be instantly available. Plus the web page itself can be cached, so the entire page and data can be displayed immediately if they are local.
- Temporary storage: In many cases, data only needs to be used while the user is browsing a set of pages and then discarded after the window is closed. SessionStorage is very convenient in this case.
IndexedDB: IndexedDB is a browser-provided local database that can be created and manipulated by web scripts. Features are as follows:
- Key-value pair storage
- Asynchronous: LocalStorage is synchronous
- Support transactions. IndexedDB supports transactions, which means that if a single transaction fails, the entire transaction is cancelled and the database is rolled back to the state before the transaction occurred, without overwriting only part of the data.
- Origin restriction: IndexedDB is subject to origin restriction and only origin Windows can be shared
- Large storage space: IndexedDB has much more storage space than LocalStorage, usually no less than 250MB or even no upper limit.
- Binary storage is supported. IndexedDB can store not only strings but also binary data (ArrayBuffer objects and Blob objects).
4. Verify login through cookies and tokens
4.1 the cookies
After the user logs in successfully, the server stores the sessionId (identity identification) in the browser cookies. Every time the client initiates a request, it will bring the sessionId, and the server knows who the request comes from.
Disadvantages:
- If you store sessions on the server, the memory overhead will increase and the scalability will be poor
- Cookies need to be set on both the front and back ends across domains
- There may be cases of CSRF(Cross-site request forgery)
4.2 token
After a successful login, the server returns a token to the client. The client stores the token and carries the token in each subsequent request. The server verifies the token and returns data.
Advantages:
- Generally not stored in the database, good scalability
- The backend can be set up to support cross-domain request headers
- Prevents CSRF(Cross-site request forgery)
Reference: Thoroughly understand cookies, sessions, and tokens
5. Common HTTP request headers
- Accept: MIME type accepted by the browser;
- Accept-charset: character set acceptable to the browser;
- Accept-encoding: Data Encoding that the browser can decode, such as gzip. Servlets can return GZIP-encoded HTML pages to gZIP-enabled browsers. In many cases this can reduce download times by 5 to 10 times;
- Accept-language: the Language desired by the browser, used when the server can provide more than one Language version;
- Authorization: Indicates the Authorization information, usually in the wwW-Authenticate header response sent by the server.
- Connection: indicates whether a persistent Connection is required. If the Servlet sees the value “keep-alive” here, or if it sees that the request is using HTTP 1.1 (which by default does persistent connections), it can take advantage of persistent connections to significantly reduce the time required to download when the page contains multiple elements (such as applets, images). To do this, the Servlet sends a Content-Length header in the reply. The simplest way to do this is to write the Content to a ByteArrayOutputStream and then calculate its size before writing it out.
- Content-length: indicates the Length of the request message body.
- Cookie: This is one of the most important request headers;
- Host: the Host and port in the initial URL;
- If-modified-since: return only If the requested content has been Modified after the specified date, otherwise return 304 “Not Modified” reply;
- Referer: Contains a URL from which the user accesses the currently requested page.
- User-agent: browser type, useful if the content returned by the Servlet is related to the browser type;
Reference: The most common HTTP headers
6. Common HTTP status codes
– | category | describe |
---|---|---|
1xx | notice | The server received the request. Please continue to execute the request |
2xx | successful | The request is successfully processed |
3xx | redirect | Additional action is required to complete the request |
4xx | Client error | Client request error, server cannot process request |
5xx | Server error | The server failed to process the request |
- 100 Continue: The server has received part of the request and is waiting for the rest, and the requester should Continue to make the request
- 101 Switching Protocols: Client request Switching protocol, server acknowledged and ready to switch
- 200 OK: The request sent by the client to the server is processed and returned
- 301 Moved Peremanently: Permanent redirection — The requested resource has been assigned a new URL and should be used later
- 302 Found: Temporary redirection — The requested resource has been assigned a new URL and is expected to use the new URL for this access
- 303 SeeOther: A new URL has been assigned to the requested resource. Use the GET method to obtain the requested resource
- 304 Not Modified: A server allows access to a resource when a client sends a conditional request
- 400 Bad Request: Syntax errors exist in the Request packet
- 401 Unauthorized: HTTP authentication is required without permission
- 403 Forbidden: The server denies the access
- 404 Not Found: Requested resource could Not be Found on the server
- 500 Inter Server Error: An Error occurred when the Server executed the request
- 502 Bad Gateway: The server acting as a Gateway or proxy received an invalid request from the remote server
- 503 Server Unavailable: The Server is temporarily overloaded or is down for maintenance, and cannot process requests
- 504 Gateway time-out: The server acting as a Gateway or proxy fails to obtain requests from the remote server in a timely manner
Reference: HTTP common status code (14 kinds)
7. Differences between GET and POST
A GET request passes parameters after the URL, while a POST request is sent to the WEB server as the physical content of an HTTP message
7.1 the difference between:
- Post is more secure (it is not part of the URL, cached, stored in server logs, and browser history)
- Post sends more data (GET has a URL length limit)
- Post can send more data types (GET can only send ASCII characters)
- Post slower than get
- Post is used to modify and write data, while GET is generally used for operations such as search sorting and screening (the search queries of Taobao and Alipay are submitted by GET). The purpose is to obtain resources and read data
7.2 If any of the following conditions are met, the POST method shall be used:
- The result of the request has persistent side effects, such as adding new rows to the database
- If you use the GET method, the data collected on the form can make the URL too long
- The data to be transmitted is not 7-bit ASCII
7.3 If any of the following conditions are met, GET method is used:
- The request is to find the resource, and the HTML form data is used only to aid the search
- Request results have no lasting side effects
- The total length of the collected data and input field names in the HTML form cannot exceed 1024 characters
8. Enter the URL what happened
-
DNS domain name resolution: Resolves a domain name into an IP address
-
Initiating A TCP connection: three-way handshake A) Ok? B) Yes, are you sure? A) Sure, connect!
-
To send an HTTP request and receive an HTTP response:
HTTP request packet format: request line + Request Header + Blank line + message body HTTP response packet format: status line + response header + blank line + message bodyCopy the code
-
Disconnecting TCP connections: Four waves A) Disconnecting? B) Ok, I’ll check it A little bit B) Ok, disconnect, bye A) Ok, bye
-
Render: The browser parses the HTML code, requests resources such as JS and CSS, and renders the page
Reference: What happens between entering the URL and loading the page? (Overview)
9. Browser rendering process
- The HTML parses the DOM tree: the DOM root node is the docementElement, corresponding to the HTML tag
- CSS parses the CSSOM tree
- According to the DOM tree and csSOM tree to build a rendering tree, render the page, the three tree construction has no absolute order condition, but at the same time loading, parsing, rendering
- If JS manipulates the DOM, the browser redraws or rearranges the page depending on the size of the action
10. Repaint, reflow
10.1 Redraw – Part of the screen will be redrawn
The render tree node changes without affecting its spatial position or size on the page. For example, the background color and font color of a div tag node change, but the width, height, and inner and outer margins of the div tag node do not change, triggering the browser to redraw.
10.2 Rearrangement (Reflux) – part of the screen will be redrawn
When a rendering tree node changes, it affects the node’s geometry properties (such as width, height, padding, margin, or float, position, display: None; And so on), resulting in changes in node positions, which triggers browser rearrangement and requires regenerating the rendering tree.
- Rearrangement must be redrawn, redrawing does not necessarily rearrange
- Rearrangements take more time and affect performance than drawing, so try to avoid excessive rearrangements
10.3 How to reduce and avoid redrawing/rearrangement
- If you want to change js dynamically, you can use cssText.
- If you want to perform complex operations on an element, you can perform “offline processing” on it, hide it first, and update it together after processing.
- Take animation elements out of the document flow, use fixed or absolute logs, and reduce the size of the rearranged Render tree.
- Do not use the table layout, because small changes can cause the entire table to be rearranged
- Don’t put dom node attribute values in a loop as loop variables
DocumentFragment page rearrangement and backflow browser render page principle and process
11. Page rendering optimization
- Keep the HTML document structure to a minimum
- A small number of first screen styles can be placed on a sticky note
- Keep the style hierarchy as simple as possible
- Scripts should be placed later to avoid blocking page loading. Asynchronous loading can be configured for scripts that do not involve DOM operations
- Reduce rearrangement and redrawing
- Reduce DOM lookups by caching DOM lookups through variables
- Transfer small images to Base64 to reduce requests
- Reduce cookie usage and request carry size
Page performance optimization
- As above, optimize the page rendering
- Reduced first screen rendering time
- Resource compression and consolidation
- Leverage the browser cache
- Static resources can be deployed to the CDN to speed up resource loading
- The DNS resolution beforehand
13. HTTP cache control
Reference: HTTP caching mechanism
14. The difference between HTTP and HTTPS
HTTPS is the secure version of HTTP. HTTP data is transmitted in plaintext, so the transmission of sensitive information is not secure. HTTPS solves this problem.
Reference: HTTPS has obvious advantages over HTTP
15. http2.0
Reference: Quick Start series: an article to get you started on HTTP2.0
16. The security
16.1 XSS Cross-site request attack
describe
- For example, when writing a blog post, insert a paragraph
<script>
- The script has attack code that gets the viewer’s cookie and sends it to the attacker’s server
countermeasures
- Escape characters, such as < for < > for & gt;
- Enabling CSP tells the browser to restrict external resource loading and execution
16.2 CSRF Cross-site request Forgery
describe
- Log in a shopping website to browse products, and the payment interface is XXX, and this interface is not verified
- If you receive an email containing an image, the SRC of the image is the paid interface
- While you’re checking your email, you’re quietly paying for strategies
- Added authentication processes including fingerprint, password, and SMS verification code
- Prevent cookies from crossing domains or using tokens for login
Reference for this article:
The Web Front-end Interview – HTTP section
Performance optimization — Caching DOM objects
Summary of common methods for page performance optimization
2019 Front-end Interview series — HTTP, browser interview questions