Summary of front-end interview questions -- continuous update!

看这里: To repost, please go to this article!

Article directory


1. html series ⭐⭐⭐⭐⭐

1. New features of H5 and new features of CSS3?

html5:

  1. First of all, in order to better practice web semantics, html5 adds
    semantic tags such as header, footer, nav, aside, section, etc.

  2. In terms of forms, in order to enhance the form, types such as color, email, data, and range are added to the input, and there are some attributes,

  3. In terms of storage, sessionStorage, localStorage, and offline storage are provided to
    facilitate data storage and retrieval on the client side through these storage methods.

  4. In terms of multimedia, audio and video elements audio and vedio are specified, as well as geolocation, canvas
    , drag and drop, web worker and websocket protocols for multi-threaded programming

New features of css3:

  1. New selectors: A variety of new selectors are introduced, such as attribute selectors, pseudo-class selectors, pseudo-element selectors, etc., to make style selection more flexible.
  2. CSS3 borders such as border-radius, box-shadow, etc.;
  3. CSS3 background such as background-size, background-origin etc;
  4. CSS3 2D, 3D conversion such as transition, transform, etc.;
  5. CSS3 animation such as animation, etc.;

2. What is HTML5, and what is the difference with HTML?

HTML5 is a new standard of HTML whose main goal is to transfer all content without any additional plugins like Flash, Silverlight etc. It includes animations, videos, rich GUIs, and more.

HTML5 is a new version of HTML created as a collaboration between the World Wide Web Consortium (W3C) and the Web Hypertext Application Technology Working Group.

the difference:

  1. From the documentation declaration type:

HTML is a long piece of code that is hard to remember. The following code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

HTML5 has only simple declarations, which are easy to remember. as follows:
<!DOCTYPE html>

  1. From the semantic structure point of view:

HTML4.0: Tags that do not reflect structural semantics are usually named like this <div id="header"></div>, which means the head of the website.

HTML5: It has great advantages in semantics. Some new tabs are provided, such as: <header><article><footer>.

3. Tell me about your understanding of the Dom tree?

  1. What is DOM?

The byte stream of the HTML file transmitted from the network to the rendering engine cannot be directly understood by the rendering engine, so it must be converted into an internal structure that the rendering engine can understand. This structure is DOM. DOM provides a structured representation of HTML documents.

In the rendering engine, DOM has three levels of functions:

  • From the perspective of the page, the DOM is the basic data structure that generates the page.
  • From the perspective of JavaScript scripting, DOM provides an interface for JavaScript scripting operations. Through this set of interfaces, JavaScript can access the DOM structure, thereby changing the structure, style and content of the document.
  • From a security perspective, DOM is a security line, and some unsafe content is rejected during the DOM parsing stage.

In short, DOM is the internal data structure that represents HTML, it connects Web pages and JavaScript scripts, and filters some unsafe content.

  1. How is the DOM tree generated?

HTML parser (HTMLParser): Responsible for converting HTML byte streams into DOM structures.

So how does the network process pass data to the HTML parser?

img

From the figure, we can know that there is a shared data channel between the network process and the rendering process, and how much data is loaded by the network process, and the data is passed to the HTML parser for analysis.

After the HTML parser receives the data (byte stream), the byte stream will be converted into DOM, the process is as follows:

img

There are three stages :

  • The byte stream is converted into Token by tokenizer. The tokenizer first converts the byte stream into Tokens, which are divided into Tag Token and Text Token.
    Note that the Token here is not the Token we understood before, here is a fragment.

  • Token is parsed as a DOM node.

  • Adds a DOM node to the DOM tree.

  1. JavaScript affects DOM generation?

We know that JavaScript can modify the DOM, and it will also affect the generation of the DOM.

  • Embedded JavaScript script For example, if we embed a tag code, the previous parsing process is the same, but when the script tag is parsed, the rendering engine judges that it is a script, and the HTML parser will suspend DOM parsing at this time, because the next JavaScript may want to modify the currently generated DOM structure.
    After pausing parsing, the JavaScript engine steps in and executes the script in the tag . After the script is executed, the HTML parser resumes the parsing process and continues to parse the subsequent content until the final DOM is generated.

  • The introduction of JavaScript files is basically the same as before, the difference is that, to execute JavaScript code after pausing parsing, you need to download this JavaScript code first .

4. How to deal with cookies when cross-domain?

From sending to returning a request requires the coordination of the browser and the server. The browser needs to bring its own request parameters to the server. After the server verifies the parameters, in addition to returning data, it may also tell the browser whether the request is cached, cookies and other information. When the request is a cross-origin request, the process is even more complicated. Next, let's take a look at what problems will arise across domains, and what kind of cooperation is required between the front and back ends.

  1. common domain

I have a friend named Xiao Wang. The front-end Xiao Wang and the back-end colleague Xiao Ma are going to jointly debug a login API. The assumption is /login; Xiao Wang happily initiated the post submission after preparing the login account and password. The result was unexpected, the response to the request was intercepted by the browser, and the browser thoughtfully threw an error on the console.

img

Xiao Wang translated it, and it turned out that it was blocked by the CORS strategy. Access-Control-Allow-OriginThis strategy roughly means that if the server allows requests from different origins, it needs to include this header in the returned response header . Otherwise, when the browser gets the response and finds that there is no such header in the response header, it will swallow the response instead of handing it over to js for further processing.

Xiao Wang told Xiaoma about this, and then Xiaoma added in the returned header

1Access-Control-Allow-Origin: *

Now Xiao Wang can finally get the returned result.

It should be noted here that the browser does not intercept the request at the request stage, but sends the request normally. After getting the response from the server, it starts to check whether there is such a header in the response header. If not, the result of the response will not go to Access-Control-Allow-Originjs go there.

  1. Cross-domain non-simple requests

Later, Xiao Wang felt that it was too troublesome to send the body in the form format in the post, and hoped to submit the request body in JSON format. Xiao Ma felt that it was just a few lines of code, so he agreed. But after Xiao Wang changed the message body to JSON, he found that it was intercepted by CORS again, and the following error was thrown:

img

In the above error report, we saw the word preflight. So what's going on here? It turns out that after modifying the request body, this cross-domain request is no longer a simple request, and a preflight request needs to be made before the request is initiated. So what is a simple request?

  • Request methods include GET, HEAD,POST
  • The response header cannot contain headers other than the CORS security header .
  • Content-Type is limited to text/plain, multipart/form-data,application/x-www-form-urlencoded

Due to the content-type of json data, this post request is no longer a simple request, and for non-simple requests, cross-domain access for all domain names was previously prohibited. So it still needs to be modified Access-Control-Allow-Originto a specific request domain name. In development mode, maybe http://localhost:3000something like that.

Xiao Ma is re-editing Access-Control-Allow-Origin, and Xiao Wang got the result of successful login again. You can jointly debug the next API.

  1. Cross-domain with cookies

The login is based on the session, that is to say, after the login is successful, the server will pass through set-cookieand set the cookie to the browser, so that the next time you visit the API under the same source, the cookie will be brought.

However, the strange thing is that Xiao Wang found that after he successfully logged in, he called another interface, but the cookie was not carried, which caused the server to fail to recognize the user information, and finally returned an error (status code 401).

  1. withCredentials

It turns out that when a browser initiates a cross-domain request , it will not take the initiative to bring cookies. If a request requires a cookie, the developer needs to set an option. Take fetch api as an example:

fetch('http://baidu.com:3000', {
    
    
    // ...
	credentials: 'include'
})

If you use xhr api to request, you need to write like this:

var invocation = new XMLHttpRequest();
var url = 'http://bar.other/resources/credentialed-content/';

function callOtherDomain(){
    
    
  if(invocation) {
    
    
    invocation.open('GET', url, true);
    invocation.withCredentials = true; // 带上cookie
    invocation.onreadystatechange = handler;
    invocation.send();
  }
}

Xiao Wang made another request after setting the request. But I found that the cookie was still not brought up. Xiao Wang had no choice but to continue to check the information on MDN, and found that a sameSite attribute needs to be included when setting-cookie.

  1. sameSite

sameSite is an attribute generated to prevent csrf attacks. If you don't know what a CSRF attack is, you can check it yourself first.

Since we need to bring a cookie in the request, we need to set the sameSite of the cookie to none when setting-cookie; and because we also need to set Secure when setting the sameSite to none, the request needs to be based on https;

The last time Xiao Wang asked Xiao Ma to appeal and change the API, the server finally recognized who the request came from and returned the correct result.

  1. Summarize

Many times, we may only pay attention to what the request body is, whether the response is returned correctly, and ignore the header part. As everyone knows, headers play an important role in caching, web security, and correct parsing results by browsers, such as a series Access-Control-Allow-*of headers in this article.

In order to make the web more secure, CORS is constantly being updated. For example, this proposal stipulates that when accessing a local network from a public network or from a private network, cross-domain headers need to be set Access-Control-Allow-Private-Network.

5. Tell me about your understanding of SSG?

SSG (Static Site Generation) refers to pre-generating static pages during construction and deploying these pages to CDN or other storage services to improve the performance and user experience of web applications.

Specifically, the implementation of SSG usually includes the following steps:

  1. In the development phase, use technologies such as template engines to create static page templates;
  2. Obtain the data to be displayed from the background API or through other channels, and fill it into the static page template to generate a complete HTML page;
  3. Use building tools (such as Gatsby, Next.js, etc.) to build static pages and generate static HTML, CSS and JavaScript files;
  4. Deploy the generated static files to the server or CDN for user access.

Compared with traditional dynamic web pages, SSG has the following advantages:

  1. Fast loading: Since the page does not need to be dynamically rendered for each request, SSG can reduce page load time, thereby improving user experience and search engine rankings;
  2. High security: Since there is no background code and database, SSG is not vulnerable to attacks such as SQL injection;
  3. Low cost: SSG can reduce website operation and maintenance costs and server burden because it does not require dynamic servers and other equipment.

It should be noted that SSG is not suitable for scenarios such as frequently updated content and dynamic interaction, but it is a good choice for performance optimization for websites with more stable content and less updates.

6. What is the process from inputting url to displaying the screen of the page?

  1. First, enter the url in the browser address bar

  2. The browser first checks the browser cache-system cache-router cache, and if there is one in the cache, it will directly display the page content on the screen. If not, skip to the third step.

  3. Before sending an http request, domain name resolution (DNS resolution) is required to obtain the corresponding IP address.

  4. The browser initiates a tcp connection to the server and establishes a tcp three-way handshake with the browser.

  5. After the handshake is successful, the browser sends an http request to the server to request a data packet.

  6. The server processes the received request and returns the data to the browser

  7. The browser receives the HTTP response

  8. Read page content, browser rendering, parsing html source code

  9. Generate Dom tree, parse css style, js interaction, render and display page

After the browser downloads the HTML, it first parses the header code, downloads the style sheet, and then continues to parse the HTML code downwards, builds a DOM tree, and downloads the style sheet at the same time. When the DOM tree is constructed, immediately start to construct the CSSOM tree. Ideally, the download speed of the style sheet is fast enough, and the DOM tree and the CSSOM tree enter a parallel process. When the two trees are constructed, the rendering tree is constructed and then drawn.

The impact of browser security parsing policies on parsing HTML:

When inline JS code is encountered when parsing HTML, it will block the construction of the DOM tree, and the JS code will be executed first; when the CSS style file is not downloaded, the browser parses HTML and encounters inline JS code. At this time, the browser Pause JS script execution, pause HTML parsing. Until the download of the CSS file is completed, the construction of the CSSOM tree is completed, and the original parsing is resumed.

JavaScript will block DOM generation, and style files will block the execution of JavaScript. Therefore, in actual projects, you need to focus on JavaScript files and style sheet files. Improper use will affect page performance.

7. What are the reasons for the long loading time of the page and how to optimize it?

  1. white screen time

White screen time: It refers to the time from when the screen is blank to when the first screen is displayed after the user clicks a link or opens the browser and enters the URL address.

  1. The importance of white screen time

When the user clicks on a link or directly enters the URL in the browser to start accessing, it starts to wait for the page to be displayed. The shorter the page rendering time, the shorter the user waits, and the faster the user perceives the page. This can greatly improve the user experience, reduce user bounce, and improve the retention rate of the page.

  1. White Screen - Performance Optimization

DNS resolution optimization: For the DNS Lookup link, we can optimize DNS resolution in a targeted manner.

  • DNS cache optimization
  • DNS Preload Policy
  • Stable and reliable DNS server

TCP Network Link Optimization: Pay More

Server-side processing optimization: Server-side processing optimization is a very large topic, and it will involve such as Redis cache, database storage optimization, various middleware in the system, and Gzip compression, etc...

Browser download, parsing, and rendering page optimization: According to the browser's downloading, parsing, and rendering process of the page, you can consider the optimization process

  • Streamline HTML code and structure as much as possible
  • Optimize CSS files and structures as much as possible
  • Be sure to place JS code reasonably, try not to use inline JS code
  • Inlining the critical CSS needed to render above-the-fold content into the HTML makes the CSS download much faster. It can be rendered after the HTML download is completed, and the page rendering time is advanced, thereby shortening the rendering time of the first screen;
  • Delay the loading of images that are not required for the first screen, and prioritize the loading of images required for the first screen (offsetTop<clientHeight)
    document.documentElement.clientHeight//Get the height of the visible area of ​​the screen
    element.offsetTop//Get the height of the element relative to the top of the document

Because JavaScript will block DOM generation, and style files will block the execution of JavaScript, so in the actual project, we need to focus on JavaScript files and style sheet files, improper use will affect page performance.

8. Have you heard about progressive jpg?

Progressive JPEG (Progressive JPEG), or PJPEG, is one of the standard's three popular compression modes.

Progressive JPEG compresses photos and graphics in a specific way, and unlike baseline JPEG, PJPEG initially gives the appearance of a blurry image when rendered in a web browser. Then it starts rendering the image bit by bit until it shows the fully rendered image. The browser actually interprets the image line by line, but provides a blurry preview of the full image in the placeholder. As the web browser's rendering engine processes the data, the contrast of the image begins to become sharper and more detailed. Until the final rendering is completed, the user will see the complete and clear image.

PJPEG can have a very meaningful psychological effect, allowing users to have something to look at instead of sitting around waiting for a large image to slowly display on the screen.
PJPEG works with most popular browsers, including Chrome, Firefox, and Internet Explorer 9 and above. Older versions of Internet Explorer had some issues displaying progressive JPEGs, but this was only a small percentage of users. Browsers that do not support the progressive JPEG format will load the photo as a regular JPEG.

9. Front-end cross-page communication, what methods do you know?

Common cross-page communication methods are as follows:

  1. Window.postMessage():
    This method allows secure cross-domain communication between different windows. This method can send a message to the specified target window and windowtrigger an messageevent on the object of the target window.

  2. LocalStorage/SessionStorage:
    These two web storage APIs can share data among all pages in the current browser window. If a page sets a storage item, other same-origin pages can access the same data by reading the storage item.

  3. BroadcastChannel API:
    This API allows communication between multiple browser tabs under the same origin. This method creates a broadcast channel, sends messages to this channel, and then onmessagereceives messages by listening to events on this channel on other pages.

  4. SharedWorker:
    SharedWorker is a mechanism provided by HTML5 to share data across pages. It is similar to ordinary Web Worker, but unlike ordinary Web Worker, SharedWorker does not serve a specific page or document, but serves multiple pages under the same source.

In addition to the above methods, there are some third-party libraries and frameworks, such as EventEmitter, Socket.io, etc., which can also be used to achieve cross-page communication, but these methods may require more configuration and usage costs.

For same-origin pages, common methods include:

  • Broadcast mode: Broadcast Channel / Service Worker / LocalStorage + StorageEvent
  • Shared storage mode: Shared Worker / IndexedDB / cookie
  • Word of mouth mode: window.open + window.opener
  • Server-based: Websocket / Comet / SSE, etc.

And for non-same-origin pages:

  • You can convert non-same-origin page communication to same-origin page communication by embedding a same-origin iframe as a "bridge".

10. What is the difference between src and href?

src is used to replace the current element, and href is used to establish a link between the current document and the referenced resource

  • src

src is the abbreviation of source, pointing to the location of external resources, the content pointed to will be embedded in the position of the current tag in the document, when the src resource is requested, the resource pointed to will be downloaded and applied to the document, such as is script, img image
<script src ="js.js"></script>
When the browser parses this element, it will suspend the download and processing of other resources until the resource is loaded, compiled, and executed. The same is true for elements such as pictures and frames, similar to embedding the pointed resource into the current tag Inside. That's why the is script is placed at the bottom instead of the head.

  • href

href is the abbreviation of Hypertext Reference, which points to the location of the network resource and establishes a link with the current element (point) or current document (link). If it is added in the document, the browser will recognize the <link href="common.css" rel='stylesheet'/>
document as an ss file, and it will be parallel Downloads resources without stopping processing of the current document. This is why it is recommended to use link to load css instead of @import.

11. What is SEO?

SEO (Search Engine Optimization), Chinese translation for search engine optimization.
Search engine optimization is a way to use the search rules of search engines to improve the natural ranking of current websites in relevant search engines.
SEO refers to the act of making reasonable planning from the perspectives of website structure, content construction plan, user interaction communication, and pages in order to obtain more free traffic from search engines, so that the website is more suitable for the indexing principles of search engines.

12. What is the function of the srcset attribute of img?

Different images are often used in responsive pages according to the screen density. At this time, the srcset attribute of the img tag is used. The srcset attribute is used to set different screen densities, and the img will dynamically add different pictures. Usage is as follows:

<img src="image-128.png" srcset="image-256.png 2x" />

Using the above code, you can load image-128.png when the screen density is 1x, and load image-256.pnq when the screen density is 2x. According to the above
implementation, you must set the image address for different screen densities. There are currently four screen densities: 1x2x and 3x4X. If you set 4 pictures for each picture, the loading will be very slow, so there is a new srcset standard. code show as below:

<img src="image-128.png" srcset="image-128.png 128w, image-256.png 256w, image-512.png 512w"sizes="(max-width: 360px) 340px, 128px” />

Among them, srCset specifies the address of the picture and the corresponding picture quality, and sizes is used to set the size zero point of the picture. For the w unit in scset, it can be regarded as image quality, if the visible area is smaller than the value of this quality, it can be used. The browser will automatically choose the smallest available image.

The syntax of sizes is as follows:
sizes="[media query] [length],[media query] [length] ...
sizes means that the default display is 128px, if the viewport width is greater than 360px, it will display 340px.

13. What are the commonly used meta tags?

metaTags are defined by nameand contentattributes, which are used to describe the properties of webpage documents, such as the author of the webpage, webpage, Guan Jie, etc. In addition to the HTTP standard nationally defined name as a consensus for everyone to use, developers can also customize the name;

Commonly used meta tags:

  1. charset , used to describe the encoding type of the HTML document
    <meta charset="UTF-8”>

  2. keywords , page keywords:
    <meta name="keywords” content="关键词” />

  3. description , page description:
    <meta name="description” content="页面描述内容”/>

  4. refresh , page redirection and refresh:
    <meta http-equiv="refresh" content="@;url=" />

  5. viewport , adapted to the mobile terminal, can control the size and proportion of the viewport:
    <meta name="viewport" content="width=device-width, initial-scale=l, maximum-scale=1">
    Among them, the content parameter has the following types:

    • width viewport : width (value/device-width)
    • height viewport : height (value/device-height)
    • initial-scale : initial zoom ratio maximum-scale : maximum zoom ratio
    • minimum-scale : the minimum zoom factor 9
    • user-scalable : Whether to allow users to zoom (yes/no)
  6. robots , search engine indexing method:
    <meta name="robots" content="index,follow" />
    Among them, the content parameter has the following types:

    • all: the file will be retrieved, and the links on the page can be queried;
    • none: the file will not be retrieved, and the links on the page cannot be queried;
    • index: the file will be retrieved;
    • follow: links on the page can be queried;
    • noindex: the file will not be retrieved;
    • nofollow: Links on the page cannot be queried.

14. What are the inline elements? What are block-level elements? What are the empty (void) elements?

  • Inline elements are: a b span img input select strong;
  • Block-level elements are: div ul ol li dl dt dd h1 h2 h3 h4 h5 h6 p;
  • An empty element , that is, an HTML element with no content. The empty element is closed in the opening tag, that is, the empty element has no closing tag:
    common ones are: , <br>, <hr>, <img>, <input>, <link>; <meta>rare
    ones are: <area>, <base>, , <col>, <colgroup>, <command>, <embed>, <keygen>, <param>, <source>, <track>.<wbr>

15. Tell me about the HTML5 drag api?

  • drastart: The main body of the event is the dragged and dropped element, which is triggered when the dragged and dropped element starts to be dragged and dropped.
  • darg: The event body is the dragged and dropped element, which is triggered when the dragged and dropped element is being dragged and dropped.
  • dragenter: The event body is the target element, which is triggered when the dragged element enters an element.
  • dragover: The event body is the target element, which is triggered when it is dragged and moved within an element.
  • dragleave: The event body is the target element, and is triggered when the dragged element moves out of the target element.
  • drop: The event body is the target element, which is triggered when the target element fully accepts the dragged and dropped element.
  • dragend: The event body is the element being dragged and dropped, which is triggered when the entire drag and drop operation ends

16、?


Two, css series ⭐⭐⭐⭐⭐

1. Understanding of BFC?

1. BFC (Block Formatting Context), that is, block-level formatting context, it is a rendering area in the page
, and has its own set of rendering rules:

  • The inner boxes will be placed one after the other vertically
  • The margins of two adjacent boxes of the same BFC will overlap, regardless of the direction.
  • The left margin of each element touches the left border of the containing block (from left to right), even for floated elements
  • BFC's area will not overlap with float's element area
  • When calculating the height of BFC, floating sub-elements also participate in the calculation
  • BFC is an isolated and independent container on the page. The child elements in the container will not affect the elements outside, and vice versa. The purpose of
    BFC is to form a space that is completely independent from the outside world, allowing the child elements will not affect outer elements

2. The conditions for triggering BFC include but are not limited to:

  • The root element, the HTML element
  • Floating element: float value is left, right
  • The overflow value is not visible, it is auto, scroll, hidden
  • display的值为inline-block、inltable-cell、table-caption、table、inlinetable、flex、inline-flex、grid、inline-grid
  • The value of position is absolute or fixed

3. Using the characteristics of BFC, we will BFCapply it in the following scenarios:

  • Prevent margin overlap (collapse)
  • clear inner float
  • Adaptive multi-column layout

2. Tell me about your understanding of the box model?

The box model is actually that the browser regards each label as a rectangular box. Each box is composed of four parts: content, inner margin, border, and outer margin. The box model is divided into standard box model
and The difference between the weird box model
: the width and height of the standard box model only include the content, not including other parts The width and height of the weird box model include the content, padding and border parts
Set the box model
border-box via the box-sizing property //weird box Model content-box //standard box model

3. How to achieve horizontal and vertical centering of elements?

Known width and height:

1. Positioning:
Absolute positioning top: 50%; left; 50%; margin negative half of its own width and height

2. Positioning:
absolute positioning top: 50%; left; 50%; transform (-50%, -50%) negative fifty percent

3. Grid grid layout
Set the parent element to display: grid; use the grid-auto-columns and grid-auto-rows attributes to set the grid cell size to auto, and then use the justify-content and align-content attributes to make the grid vertical and centered horizontally.

Unknown width and height:

2. Positioning:
element absolute positioning up, down, left, right (0) margin: auto;

3. Elastic box:
the parent element sets the flex elastic box, and then uses justify-content: center, align-items: center to center

4. Table layout
Set the parent element to display: table-cell, and the child element to display: inline-block. Use vertical and text-align to center all inline block-level elements horizontally and vertically

4. How does CSS draw a triangle? What is the principle?

Usually we will use pictures or svg to complete the triangle rendering, but if we only use css how to complete a triangle
? In fact, the implementation process does not seem to be difficult, and
the implementation process can be completed through the border:
set an element with a width and height of zero, then set its border border to 50px or larger, and finally give a color value, and set the other three borders width to zero

5. Tell me about the difference between em/px/rem/vh/vw?

The differences between em/px/rem/vh/vw are as follows:
px: absolute unit, the page is displayed in precise pixels
em: relative unit, the reference point is the font size of the parent node, if you define the font-size by yourself Calculation, 1em in the entire page is not a fixed value
rem: relative unit, which can be understood as root em, and vh and vw are calculated relative to the font size of the root node html
: mainly used for page viewport size layout, in The page layout is more convenient and simple

6. How to break away from the document flow?

Breaking away from the document flow refers to a technique of taking elements out of the layout flow of a normal HTML document so that they do not occupy the space of the document flow.
Here are a few common ways to get out of the document flow:

  1. The position attribute is absolute or fixed: use absolute positioning or fixed positioning to take the element out of the normal document flow, but it should be noted that this will cause the element to overlap with other elements, so you need to use the z-index attribute for hierarchical control .

  2. Float attribute: Floating can be used to remove elements from the normal document flow, but it should be noted that floating will affect the position and layout of subsequent elements of the element, and it is necessary to clear the floating to avoid the impact on subsequent elements.

  3. transform attribute: Use the transform attribute to perform transformation operations such as rotation and scaling on the element, and the element can be taken out of the normal document flow, but it should be noted that the element will still occupy the original space position, but it is transformed visually. If it needs to be completely removed from the document flow, it needs to be combined with absolute or fixed positioning.

  4. The display attribute is inline-block or table-cell: Using inline-block or table-cell can take the element out of the normal document flow, but it should be noted that this will turn the element into an inline block or table cell , you need to pay attention to the style adjustment during layout.

7. A complete list of css selectors?

  1. **Tag selector:** Select elements by HTML tag names, such as p, div, ul.

  2. **Class selector: **Select elements by class name, use .class, such as .container, .red-text.

  3. **ID selector: **Select elements by element ID, use #id, such as #header, #main.

  4. **Descendant selector: **Select the specified descendant element, add a space between the two selectors, such as ul li, .container p.

  5. **Child element selector: **Select the specified child element, add > after the parent element, such as .container > h1.

  6. **Adjacent sibling selector: **Select an element immediately after another element, add + after the selector, such as h1 + p.

  7. **Universal selector:** Select all elements, use *, such as *.

  8. **Attribute selector:** There are three ways to select elements through element attributes:

  • [attribute]: Select elements with specified attributes, such as [href].

  • [attribute=value]: Select elements with specified attributes and values, such as [class=container].

  • [attribute*=value]: selects elements with attributes containing the specified value, such as [class*=col].

  1. **Pseudo-class selector:** Indicates the special state or position of the element, in the following ways:
  • :hover: The style to apply when the mouse is over the element.

  • :active: The style to apply when the element is activated.

  • :focus: The style to apply to the element when it is focused.

  • :nth-child(n): The style applied to the child element at the specified position, such as li:nth-child(2) means to select the second li element.

  • :first-child: Select the first child element under the parent element.

  • :last-child: Select the last child element under the parent element.

These are commonly used CSS selectors, and different selectors can be combined to achieve more precise element selection.

8. What happens when using position:absolute in flex layout?

When using the Flex layout, if the child element is set to position: absolute, it will break away from the Flex layout and no longer occupy the space of the parent container. Therefore, the flex container ignores this element, and other child elements are arranged according to their size and flex properties.

Specifically, for a child element with position: absolute set, its position and size are calculated relative to the nearest non-static positioned ancestor element (or root element). This means that it is no longer controlled by the alignment and alignment of the flex container, but is completely free-positioning.

Below is an example:

<div class="container">
  <div class="box box-1"></div>
  <div class="box box-2"></div>
  <div class="box box-3"></div>
</div>
.container {
    
    
  display: flex;
  justify-content: center;
  align-items: center;
}
.box {
    
    
  width: 100px;
  height: 100px;
}
.box-1 {
    
    
  background-color: red;
}
.box-2 {
    
    
  background-color: blue;
  position: absolute;
  right: 0;
  top: 0;
}
.box-3 {
    
    
  background-color: green;
}

As shown above, we set position: absolute on the second child element (box-2) in the flex container, which will no longer occupy the space of the parent container and will not be controlled by the flex container.

Therefore, box-1 and box-3 will be arranged according to the alignment and arrangement of the flex container, while box-2 will be placed in the upper right corner of the parent container, and its position and size are determined by the position and top, right properties.

9. What are the meanings and usages of calc, support, and media?

calc, support, and media are three commonly used grammars and functions added by CSS3, which are used to calculate style attribute values, detect browser support for a certain feature, and set styles for different devices or media types.

  1. calc

The calc() function allows us to perform simple mathematical calculations in CSS for more flexible styling effects. It allows mathematical expressions to be used in CSS properties for easy calculations, like so:

width: calc(100% - 20px);
height: calc(50vh - 10%);

Among them, the calc() function can contain operators such as +, -, *, / and brackets, which are used to complete the basic four arithmetic operations, as well as the calculation of multiple units such as percentage, length, angle and time.

  1. @support

Support detection refers to checking whether a browser supports certain CSS properties, functions, or features. The @supports rule can be used to test whether a browser supports a certain CSS feature. Examples are as follows:

@supports (display: grid) {
    
    
  /* 支持 Grid 布局 */
  .container {
    
    
    display: grid;
    grid-template-columns: repeat(3, 1fr);
  }
}

Here, the CSS code in the @supports rule will be applied only if the browser supports the Grid layout.

  1. @media

@media rules are used to set styles for different devices or methods, and different media types. It can set different styles according to screen size, resolution, device type and other conditions, so as to provide the best user experience for different users. Examples are as follows:

@media (max-width: 768px) {
    
    
  /* 当屏幕宽度小于等于 768px 时应用的样式 */
  .container {
    
    
    width: 100%;
    margin-left: 0;
  }
}

In @media rules, we can use multiple CSS properties to set styles for specific conditions, such as max-width, min-width, orientation, resolution and other properties.
In general, calc, @support and @media are very useful new functions in CSS3, which allow developers to set styles and layouts more flexibly, and improve the responsiveness and user experience of websites.

10. About all the properties of the elastic box, and detailed explanation?

Flexbox layout is a new layout method in CSS3, which can easily handle various layout problems common in modern web pages, such as horizontal centering, vertical centering, contour layout, adaptive layout, etc. Regarding all the properties of the elastic box, the following are detailed explanations one by one:

    1. display
      sets the display mode of the flex box, the value is flex or inline-flex, where flex means a block-level flex box, and inline-flex means an inline flex box.
    1. flex-direction
      sets the direction of the main axis, and the values ​​are row (default value), row-reverse, column and column-reverse. Among them, row indicates that the main axis is horizontal, and the starting point is at the left end; row-reverse indicates that the main axis is horizontal, and the starting point is at the right end; column indicates that the main axis is vertical, and the starting point is at the upper edge; column-reverse indicates that the main axis is vertical, and the starting point is at the lower edge.
    1. flex-wrap
      sets whether and how to wrap the line, the values ​​are nowrap (default value), wrap and wrap-reverse. Among them, nowrap means no line break; wrap means line break in order; wrap-reverse means line break in reverse order.
    1. flex-flow
      flex-flow is the short form of flex-direction and flex-wrap, its syntax is: flex-flow: ; For example: flex-flow: row wrap; means that the direction of the main axis is horizontal, and wrap at the same time.
    1. justify-content
      sets the alignment on the main axis, and the values ​​are flex-start (default value), flex-end, center, space-between and space-around. Among them, flex-start means left alignment, flex-end means right alignment, center means center alignment, space-between means both ends are aligned and the spacing between items is equal, and space-around means that the spacing on both sides of each item is equal and the same as other Items are spaced differently.
    1. align-items
      sets the alignment on the cross axis, and the values ​​are flex-start, flex-end, center, baseline and stretch. Among them, flex-start means top alignment, flex-end means bottom alignment, center means center alignment, baseline means baseline alignment, and stretch means that the item height automatically fills the entire container.
    1. align-content
      sets the alignment of multiple axes (when there are multiple lines), and the value is the same as justify-content. This property has no effect if there is only one row.

Properties of flexbox items

    1. order
      sets the sorting order of the items, the smaller the value, the higher the front, the default is 0.
    1. flex-grow
      sets the magnification ratio of the item, and the default is 0, that is, if there is remaining space, it will not be magnified.
    1. flex-shrink
      sets the reduction ratio of the item, the default is 1, that is, if there is insufficient space, the item will shrink.
    1. flex-basis
      sets the baseline value of the item, the main axis space occupied by the item before allocating excess space, and the default value is auto, which means it is calculated by the item itself.
    1. flex
      flex is shorthand for flex-grow, flex-shrink and flex-basis, its syntax is: flex: none | [ <'flex-grow'> <'flex-shrink'>? || <'flex-basis' > ], for example: flex: 1 0 auto; indicates an item with an enlargement ratio of 1, a reduction ratio of 0, and a base value of auto.
    1. align-self
      sets the alignment of a single item in the direction of the cross axis, the value is the same as align-items, but it only works on a single item, not the entire container.

11. What properties can css inherit?

In CSS, some properties can be inherited, and child elements will inherit these values ​​from their parent elements to avoid writing the same style repeatedly. The following are some common attributes that can be inherited by child elements:

  1. font family ( font-family)

The font family set on the parent element will be inherited by the child elements, unless the child element has its own defined font family.

  1. font size ( font-size)

The font size defined on the parent element can also be inherited by the child elements, but while inheriting, the child elements may calculate the specific font size based on their own box model, thus obtaining different sizes.

  1. weight ( font-weight)

Like font family and font size, child elements can also inherit font-weightvalues ​​from their parents.

  1. line height ( line-height)

Line height is a measure of the height of text within a line. line-heightSince the value is set by default normal(usually 1.2 to 1.5 times the current font size), the line height set on the parent element is usually also inherited by the child elements.

  1. color ( color)

The text color set by the parent element can also be inherited by the child element, but in many cases the child element will override the parent color through the class name or ID selector.

  1. list style ( list-style)

If list-stylethe attribute is defined on a ulor olelement, its child elements can also inherit the attribute value.

  1. Text orientation ( direction), text alignment ( text-align), and text indentation ( text-indent)

The three properties of text direction, text alignment and text indentation can also be inherited by child elements. Note, however, that when setting alignment, the actual position of an inline element may be calculated based on its own internal box model rather than inherited from the parent.

Not all CSS properties can be inherited, and some properties are not designed to be inherited, such as width, height, backgroundand so on.

12、


3. javaScript series ⭐⭐⭐⭐⭐

1. Closure?

A closure is a function that can read variables inside other functions. A closure is a function that has access to variables in the scope of another function. The most common way to create a closure is to create another function inside a function, through another function. A function accesses the local variables of this function, and the use of closures can break through the chain of scope

Closure features:

  • Nesting functions within functions
  • Inner functions can refer to outer parameters and variables
  • Parameters and variables are not garbage collected

Talk about your understanding of closures:

  • The main purpose of using closures is to design private methods and variables. The advantage of closures is that they can avoid the pollution of global variables. The disadvantage is that closures will stay in memory and increase memory usage. Improper use can easily cause memory leaks. In js, functions are closures, and only functions have the concept of scope

  • There are two biggest uses of closures, one is to read the variables inside the function, and the other is to keep these variables in memory at all times

  • Another use of closures is to encapsulate private properties and private methods of objects

Benefits: Encapsulation and caching can be achieved;

Disadvantages: memory consumption, improper use will cause memory overflow

Points to note when using closures:

Since the closure will cause the variables in the function to be stored in memory, the memory consumption is very large, so the closure cannot be abused, otherwise it will cause performance problems on the web page, which may cause memory leaks in IE. The solution is to exit the function
before , delete all unused local variables

Such as the common anti-shake throttling

// 防抖
function debounce(fn, delay = 300) {
    
    
  let timer; //闭包引用的外界变量
  return function () {
    
    
    const args = arguments;
    if (timer) {
    
    
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
    
    
      fn.apply(this, args);
    }, delay);
  };
}

Closures can be used to simulate block-level scope in JavaScript

function outputNumbers(count) {
    
    
  (function () {
    
    
    for (var i = 0; i < count; i++) {
    
    
      alert(i);
    }
  })();
  alert(i); //导致一个错误!
}

Closures can be used to create private variables in objects

var aaa = (function () {
    
    
  var a = 1;
  function bbb() {
    
    
    a++;
    console.log(a);
  }
  function ccc() {
    
    
    a++;
    console.log(a);
  }
  return {
    
    
    b: bbb, //json结构
    c: ccc,
  };
})();
console.log(aaa.a); //undefined
aaa.b(); //2
aaa.c(); //3

2. Tell me about your understanding of the scope chain?

  • The role of the scope chain is to ensure that the variables and functions that have the right to access in the execution environment are in order. The variables of the scope chain can only be accessed upwards, and the variables will be terminated when they access the window object. Allowed
  • Simply put, the scope is the accessible range of variables and functions, that is, the scope controls the visibility and life cycle of variables and functions

3、?

4、?

5、?


4. Vue series ⭐⭐⭐

1、?

2、?

3、?

4、?

5、?


Five, react series ⭐⭐⭐

1. React event mechanism?

<div onClick={ 
        this.handleClick.bind(this)}>点我</div>

React does not bind the dlick event to the real DOM of the div, but listens to all events outside the document. When an event occurs and bubbles out of the document, React encapsulates the event content and hands it over to the real processing The function runs. This method not only reduces memory consumption, but also uniformly subscribes and removes events when the component is pending destruction.

In addition, the event that bubbles up to the document is not a native browser event, but a synthetic event (SyntheticEvent) implemented by react itself. So if you don't want event bubbling, you should call the event, preventDefault0 method instead of calling the event.stopProppagation0 method

2、?

3、?

4、?

5、?


6. webpack series ⭐⭐⭐

1. What is the construction process and properties of webpack?

Webpack is a popular front-end bundling tool for merging multiple JavaScript files and other resources into one or more bundle.js files for production use. The following is the build process and common properties of Webpack:

  1. Build process:

Webpack is mainly divided into the following steps:

  • Parse the configuration file: Webpack will read the configuration file provided by the user, and perform follow-up operations according to the configuration information.
  • Parsing module dependencies: Webpack will parse the dependencies between all modules and generate a dependency graph.
  • Loading modules: Webpack will load each module according to the dependency graph.
  • Convert code: Webpack can convert each module through loader, such as converting ES6 code to ES5 code.
  • Generate code blocks: Webpack will generate some code blocks according to the dependencies between codes, and each code block contains the code of one or more modules.
  • Output files: Webpack will combine all generated code chunks into one or more output files.
  1. Attributes:

Some common properties of Webpack are as follows:

  • entry: The path of the entry file, from which Webpack will resolve all dependencies.
  • output: The configuration of the packaged generated file, which includes information such as file name and output path.
  • module: Configure the processing rules of various modules, and usually use different types of loaders to implement file conversion.
  • resolve: Configure information such as the priority and default file extension of Webpack when searching for modules.
  • plugins: Configure the plugins used by Webpack. Plugins can be used to complete various automation tasks, such as compressing files, merging code blocks, and so on.

2、?

3、?

4、?

5、?


7. uniapp series ⭐⭐

1、?

2、?

3、?

4、?

5、?


Seven, jquery series ⭐⭐

1. Is there any difference between $.get() submission and $.post() submission in jquery?

Same point:

All are asynchronous requests to obtain data from the server;

Different score:

  1. The request method is different: The $.get() method uses the GET method to make an asynchronous request. The $.post() method uses the POST method to make an asynchronous request.

  2. Parameter transmission methods are different: GET requests will pass parameters after the URL, while POST requests are sent to the Web server as the entity content of the HTTP message, and this transmission is invisible to the user.

  3. The size of the data transfer is different: the size of the data transferred by the get method cannot exceed 2KB, while the size of the POST is much larger

  4. Security issues: The data requested by the GET method will be cached by the browser, so there are security issues.

2. What is the difference between the $(document).ready() method and window.onload?

  1. The window.onload method is executed after all elements in the web page (including all associated files of the elements) are fully loaded into the browser.
  2. The $(document).ready() method can manipulate the DOM as soon as it is ready to load and call functions that perform bindings.

3、?

4、?

5、?


8. WeChat mini-program series ⭐⭐

1. Briefly describe the relevant file types of the WeChat Mini Program?

The WeChat Mini Program project structure mainly has four file types, as follows:

  1. WXML can build the structure of the page

  2. WXSS is a style language used to describe WXML component styles

  3. js logic processing, network request

  4. json applet configuration file

  5. app.json is used as the configuration file entry, the global configuration of the entire applet.

  6. app.js must have this file, no error will be reported

  7. app.wxss global page style setting, the style set in app.wxss can take effect on all pages of the applet

2. How does the applet follow the event to pass the value?

Bind = value on the page tag data-key, and then the binding event passes e.Target.dataset.keyto get the value bound on the tag (he Gait)

3. What is the difference between the applet WXSS and CSS?

  1. The wxss background image can only be imported from external links, and local images cannot be used.
  2. Applets can use @import to import external style files, and the address is a relative path.
  3. The size unit is rpx, and rpx is a responsive pixel, which can be adapted according to the screen width

4. How is the two-way binding of applets different from that of Vue?

The applet directly uses this.data.key = value and cannot be updated to the view,
it must be used this.setData({ key :value })to update the value

5. Please talk about the life cycle function of the applet?

  • onLoad(angrude): Triggered when the page loads
  • onShow(): Triggered when the page is displayed/cut to the foreground
  • onHide(): Triggered when the page hides/cuts into the background
  • onReady (An Rui Di): Triggered when the page is rendered for the first time
  • onUnload (Ang Ang Lou): Triggered when the page is unloaded
  • onPullDownRefresh (OnPullDownRefresh): hook function for pull-down refresh
  • onReachBottom (OnReachBottom): the hook function for turning up to the bottom

6. How does the applet implement pull-down refresh?

Option 1:

In app.json, enablePullDownRefreshset【啊a波普丹瑞fishit】to true to enable global pull-down refresh.
Or set enablePullDownRefresh to true in the component json to enable single-component pull-down refresh.

Option two:

scroll-view: Use this scrolling component to customize the refresh. Through the bindscrolltoupper(version of the dead class meat spit out) property, when scrolling to the top left, it will trigger the scrolltoupper[Zi class meat spit out] event, use this property to implement the pull-down refresh function.

7. What is the difference between bindtap and catchtap?

Same point:

They are all click events in the applet.

difference:

bindtap【Tapu by Office】Will not stop bubbling, catchtapit can stop bubbling. (Eat tetaipu).

8. What methods does the applet have for transferring data?

Option 1: Use global variables

this.globalDataPut the data to be stored in (attic blog) in app.js. Introduce const app (Kangso Aipu) = getApp() in the head of component.js to obtain global variables, and then use app. globalData.keyto obtain and assign values.

Option 2: Use routing

When using wx.navigateTo and wx.redirectTo (Ruidi RedirectTo), you can splicing parameter variables after the url, and then get the passed values ​​through parameters in the onLoad lifecycle of the target page.

Solution 3: Use local storage

9. Routing and its difference in WeChat Mini Program?

wx.navigateTo (milk is for special spit): Keep the current page and jump to a page in the application. But can't jump to the tabbar page

wx.redirectTo( Rui De Rui Ke Te spit): close the current page, jump to a page in the application. But jumping to the tabbar page is not allowed

wx.switchTab (dead maintain Tab): Jump to the tabBar page and close all other non-tabBar pages

wx.navigateBack() closes the current page and returns to the previous page or multi-level page. wx.reLaunch(): Close all pages and open a certain page in the application (Rui Laochi)

10. Briefly describe the difference between wx:if and hidden?

  1. wx:if dynamically creates or destroys the corresponding UI structure
  2. wx: If the condition is false, do nothing; when it is true, the local rendering starts
  3. hidden Simple control of display and hiding of components
  4. wx:if has a higher switching cost and hidden has a higher initial rendering cost. In the case of frequent switching, it is better to use hidden, and wx:if is better if the runtime conditions are unlikely to change

11. App.json global configuration file description

pages : used to store all the page paths of the current applet
window: the top background color and text color configuration of all pages of the applet
tabBar: the Tab at the bottom of the applet, at most 5, at least 2

12. How to encapsulate Mini Program requests

Encapsulate the wx.request request to pass the required parameters, encapsulate the common methods POST, GET, finally export these methods and create a new api.js file, import the encapsulated method, and then call the corresponding method, Pass data.

Summarize:

Create a new utils (oh set) directory in the src directory, create a new request.js in the directory, and first obtain an instance of the entire applet in request.js to ensure that all methods of wx can be called, and define requests such as get and post method, and then set wx.showToast (toast) in the get or post request method, and then implement the get or post request through wx.request, and close the loading (roof) in success (sex), Then return the acquired data in the form of a callback

Use require to import at the last call

13. Briefly describe the operating mechanism of the WeChat Mini Program?

Hot start:
If the user has already opened a certain applet and opens the applet again within a certain period of time, we no longer need to restart it at this time, which requires switching the applet opened in the background to the foreground use.

Cold start:
When the user opens the Mini Program for the first time or is opened again after being actively destroyed by WeChat, the Mini Program needs to be reloaded and started.

14. When will the Mini Program be actively destroyed?

After the applet enters the background, the client will help us maintain our state for a certain period of time, and 超过五分钟will be actively destroyed by WeChat. The official has not clearly stated when it will be destroyed, and the performance of different models is different.

When developing in 2019: There is no description in the official document, but after inquiry, it generally refers to within 5 minutes. When developing in 2020: There is no description in the official document, and there is no fixed time for testing Android. If there is enough memory, sometimes a day It's still there, sometimes it's gone after a few minutes

9. Network related series⭐

1. Why does tcp shake hands three times and wave four times?

As a reliable transmission protocol, TCP requires some status confirmation and control during connection establishment and disconnection. Therefore, in the process of establishing and disconnecting a TCP connection, three handshakes and four handshakes are required.

Three-way handshake:

  1. The first handshake: the client sends a connection request segment (SYN) to the server.

  2. The second handshake: After receiving the request, the server sends back a receipt acknowledgment segment (ACK) to the client and sends a connection request segment (SYN).

  3. The third handshake: After receiving the acknowledgment message segment, the client sends back a acknowledgment message segment (ACK) to the server.

In this way, the two parties complete the three-way handshake,

The TCP connection is established successfully. The purpose of the three-way handshake is to ensure that both parties can receive each other's messages and can establish a connection correctly.

Wave four times:

  1. The first wave: the client sends a request segment (FIN) to close the connection to the server.

  2. The second wave: After receiving the request, the server sends an acknowledgment segment (ACK) back to the client.

  3. The third wave: the server sends a request segment (FIN) to close the connection to the client.

  4. The fourth wave: After receiving the request, the client sends an acknowledgment segment (ACK) to the server.

After completing four handshakes, the TCP connection is disconnected.

The purpose of the four hand waves is to ensure that both parties know that the connection has been disconnected and that all connection resources are released.
It can be seen that the establishment and disconnection of the TCP connection requires some status confirmation and control, so three handshakes and four handshakes are required. This ensures the reliability and correctness of the connection.

2. What is the difference between GET and POST?

GET and POST are two commonly used request methods in the HTTP protocol. They have the following differences:

1. Parameter position:
The parameters of the GET request are concatenated in the URL, while the parameters of the POST request are passed in the request body.

2. Request method:

The GET request is to request data from the server through the URL, and the parameter is passed through the question mark "?" in the URL. The POST request is to submit the data to the server in the HTTP request body.

3. Request length:

GET requests do not have a request body, so the length of the request is limited, and most browsers currently limit it to 2048 characters; while POST requests have no limit, but the actual situation is generally adjusted due to server restrictions.

4. Security:

GET requests will expose parameters on the URL, which is vulnerable to hijacking and attacks; while POST requests are more secure than GET because of the existence of the request body.

5. Cache:

GET requests can be cached by the browser. When the same URL is requested next time, the browser will directly fetch the data from the cache; while POST requests will not be cached, and each request needs to retransmit the data.

3、?

4、?

5、?

Nine, other ⭐⭐

1、?

2、?

3、?

4、?

5、?


Please add a picture description

Guess you like

Origin blog.csdn.net/weixin_61102579/article/details/130556068