He interviewed a lot of front-end practitioners, and his resume was flat and bland. He also had all the skills that others knew, and seemed to have some knowledge of everything. Some will be invited to have a face-to-face chat, while others will refuse directly (if it is a job requiring independent project completion in the company, the resume contains a lot of DEMO projects during study, but there is no real project, this kind of resume will generally be rejected).
When we go to a company for an interview, the interviewer has a great initiative, the interviewer belongs to the attack side, the job seeker belongs to the defense side, we can not study all directions very deep, so the best way is to play to the strengths and avoid the weaknesses, recommend everyone to be a tent type person, not a bucket type person; There are so many jobs in the market, what we need to do is to find the career that suits our strengths!
When interviewing, you must not be hard and rigid with the interviewer. You can exaggerate yourself moderately, but you must not think that you are skilled and crazy. Even if you’re one in a million and the interviewer feels uncomfortable working with you, it’s not that difficult to turn you down.
If you meet your expected salary offer, don’t hesitate, to directly, but in time, push back a bit, can after a week, ten days, this paragraph of time to continue the interview, then salary will have to find than they promised to offer salary, if encounter during their more satisfied with the offer, Find the one you’re most interested in in the offer you agreed to.
directory
HTML interview questions
CSS interview questions
JavaScript interview questions
Network communication interview questions
JQuery interview questions
Vue. Js interview questions
The React. Js interview questions
Tool interview questions
Algorithmic interview questions
Comprehensive interview questions
My favorite interviewee
HTML interview questions
What’s new in HTML5?
HTML4 specifies three declaration modes: strict mode, transition mode and frameset mode;
HTML5, since it is not a subset of SGML, only requires
2. Better semantic content tags. The header/footer/article, etc
3. Audio and Video API
4. Form controls:
HTML5 has several new form input types. These new features provide better input control and validation.
- color
- date
- datetime
- datetime-local
- month
- number
- range
- search
- tel
- time
- url
- week
5.5 API- localStorage, localStorage for long-term data storage, more commonly used, temporary storage sessionStorage, automatically deleted after the browser is closed, the actual work of the use of few scenarios.
Canvas, Canvas, figure,figcaption.
Geolocation. The Geolocation API allows users to provide their location to Web applications. For privacy reasons, users are asked for permission before reporting their location.
Drag and drop. The HTML Drag and drop interface enables applications to use Drag and drop in the browser. For example, with these features, the user can select draggable elements with the mouse, drag elements to place elements, and place them by releasing mouse buttons. A translucent representation of a draggable element follows the mouse pointer during a drag operation.
Web Workers. Webworker, websocket, Geolocation. When a script is executed on an HTML page, the status of the page is unresponsive until the script is complete. Web workers are JavaScript running in the background, independent of other scripts, and do not affect page performance. You can continue to do whatever you want: click, select content, and so on, while the Web worker runs in the background.
Doctype? How to distinguish strict mode from promiscuous mode? What do they mean?
A:
- When the page is loaded, link is loaded at the same time, and when the @imort page is loaded, link is added at the same time
- The CSS referenced by @import will wait until the page is loaded. Import is only visible in IE5
- Link is an XHTML tag. The link style has more weight than @import
- heavy
<! DOCTYPE>
The declaration is first in the document, in<html>
Tag before. Tell the browser’s parser, what document type specification is used to parse this document- Strict mode typesetting and JS mode of operation are run to the highest standards supported by the browser
- In promiscuous mode, pages are displayed in a loosely backward compatible manner. Emulate the behavior of older browsers in case the site doesn’t work. A non-existent or improperly formatted DOCTYPE will cause the document to be rendered in promiscuous mode
How to implement communication between multiple tabs in the browser?
Call localStorge, cookies and other local storage methods;
-
1. Window. opener can be used in page B to obtain the window handle of page A, which can be used to call objects and functions in page A.
- OnClosePageB js functions are defined, such as A page in the page B can use window. The opener. OnClosePageB for callback.
-
2. Use window.showModalDialog(sURL [, vArguments] [,sFeatures]) to open new Windows. Where the vArguments parameter can be used to pass parameters to dialog boxes. You can pass any type of argument, including arrays, functions, and so on. The dialog box calls window.dialogArguments to get the arguments passed in.
-
3. If HTML5 is supported, it is recommended to use local storage, which supports an event method window.onstorage, as long as one window modifies the local storage, other homologous Windows will trigger this event.
Conclusion:
- WebSocket, SharedWorker;
- You can also call localStorge, cookies and other local storage methods.
- Localstorge fires an event whenever it is added, modified, or deleted from another browsing context,
- We monitor the event, control its value to carry on the page information communication;
- Quirks: Safari throws a QuotaExceededError exception when setting localStorge in traceless mode;
Method 1: Call localStorge
Label 1:
<input id="name">
<input type="button" id="btn" value="Submit">
Copy the code
<script type="text/javascript">
$(function(){$("#btn").click(function(){
var name=$("#name").val();
localStorage.setItem("name", name); // Store the required information
});
});
</script>
Copy the code
Label 2:
$(function(){
window.addEventListener("storage".function(event){
console.log(event.key + "=" + event.newValue);
}); // Use storage events to listen for adding, modifying, and deleting actions
});
Copy the code
Method 2: Use cookie+setInterval
The information to be transmitted is stored in the cookie, and the cookie information can be read at certain intervals to obtain the information to be transmitted at any time.
Label 1:
$(function(){$("#btn").click(function(){
var name=$("#name").val();
document.cookie="name="+name;
});
});
Copy the code
Label 2:
$(function(){
function getCookie(key) {
return JSON.parse("{\" " + document.cookie.replace(/; \s+/gim."\ \", "").replace(/=/gim."\", \ "") + "\"}")[key];
}
setInterval(function(){
console.log("name=" + getCookie("name"));
}, 10000);
});
Copy the code
What are the inline elements? What are block-level elements? What are the void elements? What is the difference between a row element and a block element?
A:
- The line elements are: A B SPAN IMG input select strong
- Block level elements are: div ul OL Li DL dt DD H1 H2 H3 H4… p
- Empty element: br, HR IMG input link meta
- The width and height of elements in a row cannot be set
- Block-level elements can be set to a width and height that is exclusive to a row
What is the difference between SRC and href?
A:
-
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, short for source, refers to the location of an external resource, which will be embedded in the document at the current tag location. SRC resources are downloaded and applied to documents when requested, such as JAVASCRIPT scripts, IMG images, and frame elements
<script src ="js.js"></script>
When the browser parses this element, it pauses the rest- Download and process resources until the resource is loaded, compiled, executed, images, frames and other elements
- This is similar to embedding the pointed resource within the current tag. Is that why js scripts are at the bottom
- Part instead of head
-
Href is short for Hypertext Reference. It refers to the location of the web resource and establishes a link between the current element (anchor) or the current document (link) if we add it to the document
-
Then the browser recognizes the document as a CSS file, downloads the resources in parallel and does not stop processing the current document. Is this why it is recommended to load CSS using link rather than @import
What is the difference between cookies, sessionStorage and localStorage?
A:
- Cookies are data stored (usually encrypted) on a user’s Client Side by a website to identify the user.
- Cookie data is always carried in the same HTTP request (even if it is not needed) and is passed back and forth between the browser and the server.
- SessionStorage and localStorage do not automatically send data to the server and only store data locally.
Storage size
- Cookie data size cannot exceed 4K.
- SessionStorage and localStorage, while also limited in size, are much larger than cookies, reaching 5M or more.
Prison time
- LocalStorage stores persistent data. Data will not be lost after the browser is closed unless the data is actively deleted.
- SessionStorage data is automatically deleted after the current browser window is closed.
- Cookie The cookie set remains valid until the expiration time, even if the window or browser is closed
How does HTML5 offline storage work?
A:
Similar to the storage
LocalStorage stores data for a long time and does not lose data after the browser is closed. SessionStorage data is automatically deleted after the browser is closed.
Offline storage
One of two ways
- HTML5 offline storage
The appcache file
【 ghost 】 service-worker
The standard of
HTML5 offline storageThe appcache file
【 ghost 】
When the user is not connected to the Internet, the site or application can be accessed normally. When the user is connected to the Internet, the cache file on the user machine can be updated.
How it works: HTML5 offline storage is based on a new one. The caching mechanism (not storage technology) of the AppCache file, which stores resources offline through parsed listings on the file, and these resources are stored like cookies.
Later, when the network is offline, the browser displays the data stored offline.
How to use
-
Add a manifest attribute to the page header as shown below
-
2. Write offline storage resources in the cache.manifest file
CACHE MANIFEST # v0.11 CACHE: js/app.js css/style.css NETWORK: resourse/logo.png FALLBACK: / /offline.html Copy the code
-
3. In offline state, operate window.applicationCache to implement requirements.
service-worker
You can refer to
- www.alloyteam.com/2019/07/web…
- Developer.mozilla.org/zh-CN/docs/…
How to deal with 1px rendering 2px on mobile?
A:
The viewport attribute in the meta tag is set to initial-scale 1
Rem according to the standard design draft, plus the use of Transfrome scale(0.5) to reduce twice; 2 Global Processing
The viewport attribute in the meta tag is set to initial-scale 0.5
Rem according to the design standards can go
explain
When UI designers design, the 1px (real pixels) they draw is actually a 0.5px(CSS) line or border. But he didn’t think so. He thought he had drawn a 1px line, because the size of the drawing itself was twice the size of the screen. If the width of the phone’s retina screen is 320×480 wide, but the actual size is 640×960 wide, the designer must have designed the screen according to 640×960. But when the front-end engineer writes the code, all CSS is written in 320×480, write 1px(CSS) and the browser automatically changes to 2px (real pixels).
So why can’t front-end engineers just write 0.5px(CSS)? Because on older systems, writing 0.5px(CSS) was interpreted by the browser as 0px(CSS) and there was no border. So it’s only 1px(CSS), which is actually twice the width of the 1px(real pixels) that the designer drew on the screen, so the designer thinks this line is too thick and not the same as his design. In the new version of the system, 0.5px(CSS) writing is gradually supported. So if a designer designs a 1px (real pixels) line on a large drawing, the front end engineer just divides it by 2 and writes 0.5px(CSS).
Another explanation
The fact that it is not thicker is 1px in CSS units. For devices with a DPR of 2, the minimum it can actually display is 0.5px.
The 1px that the designer says is for the physical pixels of the device, which translates to 0.5 pixels for CSS pixels.
In summary, background:1px solid black is the same thickness on any screen, but the Retina screen can show a thinner border, and then the designer doesn’t want you to change it. .
How does the browser render the page?
A:
Parsing HTML files to create DOM trees
Top-down, any style encountered (link, style) and script will block (external styles do not block subsequent loading of external scripts).
Parsing the CSS
Priority: browser default Settings < user Settings < external style < inline style < style in HTML;
Building a Render tree
Combine CSS with DOM to build Render Tree
Layout and drawing
Layout and draw, Repaint and reflow
How to write high-performance HTML?
A:
Avoid Iframe
An Iframe, also known as an inline frame, allows you to embed one HTML document into another. The advantage of using iframe is that the embedded document can be completely independent of its parent document. With this feature, we can usually make the browser simulate multi-threading. It is important to note that using iframe does not increase the number of parallel downloads under the same domain name. Even across Windows or tabs, this is true in all major browsers. It also undermines the benefits of iframe.
The iframe element blocks the parent document onload event during page loading, and developers typically initiate UI actions when the onload event is triggered. For example, set the focus of the login area. Because users are used to waiting for this action, it is important to make the onLoad event fire as quickly as possible to make the user wait as long as possible. Unfortunately, in some browsers, the Unload event can only fire after the OnLoad event has been fired. If the OnLoad event has not been fired for a long time and the user has left the current page, Then the UNLOAD event will never fire. Is there a way to prevent the onLoad event from being blocked by iframe? A simple solution to avoid the onload event blocking is to use JavaScript to dynamically load the iframe element or to dynamically set the iframe SRC attribute:
<iframe id=iframe1 ></iframe>
documentDocument.getelementbyid (' iframe1). SetAttribute (' SRC ', 'url');Copy the code
However, it only works in advanced browsers, not Internet Explorer 8 and below. In addition, it is important to know that iframe is one of the most resource-consuming elements in A document. In Steve Souders’ tests, 100 A, DIV, SCRIPT, STYLE and Iframe elements were loaded on the test page. It has been run 10 times in Chrome, Firefox, Internet Explorer, Opera, and Safari. It turns out that creating an iframe element is one or two orders of magnitude more expensive than creating other types of DOM elements. All DOM elements are empty in the test. Loading large scripts or style blocks may take longer than loading certain IFrame elements, but benchmarking results show that even empty iframes are expensive and should be avoided due to their high overhead. Especially for mobile devices, most of which have limited CPU and memory, iframe should be avoided.
Avoid empty link properties
An empty link attribute is an img, link, script, ifrrame element whose SRC or href attribute is set but whose attribute is empty. For example,
- Internet Explorer 8 and later only have problems with img-type elements. Internet Explorer will resolve the empty img address to the directory address of the current page address. For example, if the current page address is example.com/dir/page.ht… The empty address is resolved to the example.com/dir/ address and requested.
- Earlier versions of the Webkit kernel browser and Firefox resolve the empty address to the current page address. If a page has multiple empty link attribute elements, the server for the current page will be requested multiple times, increasing the load on the server. This problem may be more serious on ios and Android mobile browsers than desktop browsers, which are more active in kernel updates.
- Fortunately, all major browsers resolve the empty address to the about:blank address when the SRC attribute of the iframe is null, without making additional requests to the server.
Avoid deep nesting of nodes
Deeply nested nodes tend to require more memory footprint during initial builds and are slower to traverse nodes due to the way the browser builds DOM documents. For example, the following HTML code:
<html>
<body>
<p>
Hello World
</p>
<div> <img src="example.png"/></div>
</body>
</html>
Copy the code
Through parsing by the browser’s HTML parser, the browser stores the entire HTML document structure as a DOM tree. The deeper the nesting level of document nodes is, the deeper the DOM tree is built.
Reduce HTML document size
The most obvious way to improve download speed is to reduce file sizes, especially by compressing JavaScript and CSS code embedded in HTML documents, which can make pages much smaller. In addition, there are several ways to reduce the size of your HTML document:
- Delete blank Spaces, empty lines and comments that have no effect on the results of the HTM document
- Avoid Table layout
- Using HTML 5
Explicitly specifies the document character set
Specifying the character set at the beginning of an HTML page helps browsers start parsing the HTML code immediately. HTML documents are usually parsed as a sequence of strings with character set-encoded information sent over the Internet. The character set encoding is specified in the HTTP response header, or in an HTML tag. Based on the acquired character set, the browser interprets the encoding into characters that can be displayed on the screen. If the browser does not know the coded character set of the page, it will usually cache the byte stream before executing the script and rendering the page, and then search for the parsable character set or parse the page code with the default character set, which can consume unnecessary time. To avoid the browser spending time searching for the appropriate character set to decode, it is best to always specify the page character set explicitly in the document.
Explicitly sets the width and height of the image
When the browser loads the HTML code for a page, it is sometimes necessary to locate the layout of the page before the image is downloaded.
If the image in the HTML does not specify a size (width and height), or if the size described in the code does not match the size of the actual image, the browser will have to “backtrack” the image and redisplay it after the image has been downloaded, which can take extra time.
Therefore, it is best to specify the size of every image on the page, whether in the < IMG > tag of the page HTML, or in the CSS.
<img src="hello.png" width="400" height="300">
Copy the code
Avoid script blocking loading
When a browser parses a regular script tag, it waits for the script to load before parsing, and subsequent HTML code has to wait. To avoid blocking loading, place steps at the end of the document, such as inserting a script tag before the body closing tag:
<script src="example.js" ></script>
</body>
Copy the code
Pros and cons of iframe?
A:
- Iframe blocks the Onload event on the main page;
- Iframe and the home page share the connection pool, and browsers have restrictions on connections to the same domain, so parallel page loading can be affected.
- These two disadvantages need to be considered before using iframe. If you need to use an iframe, it is best to use javascript to dynamically add the SRC attribute value to the iframe to avoid these two problems.
What is the difference between Canvas and SVG graphics?
A: Canvas and SVG can both draw graphics on a browser.
In other words, any shape drawn with SVG can be remembered and manipulated. The browser can display it again, but the Canvas is forgotten after drawn. Once drawn, you cannot access the pixel and manipulate it. Users want to operate its Canvas, which is used to draw and forget field paintings like animation and games.
SVG needs to record coordinates for subsequent operations, so it is slow.
Canvas is faster because there is no task to remember future events.
We can use event handlers for drawing objects and we can’t use event handlers for drawing objects because we don’t have their reference resolution independent resolution dependencies
- SVG is not exclusive to HTML5, there was SVG before HTML5.
- The extension of the SVG file is “.svg “.
- SVG draws images that are enlarged without degrading image quality.
- SVG images often make small ICONS and dynamic renderings in web pages.
What about meta tags?
Answer: the core
Some meta information (name/value pairs) provided to the page to help SEO.
Attribute values
name
The name in the name/value pair. Author, Description, Keywords, Generator, Revised, Others. Associate the Content property with a name.
http-equiv
In the absence of a name, the value of this attribute is taken. Content-type, Expires, Refresh, set-cookie. Associate the Content property with the HTTP header
content
The value in the name/value pair can be any valid string. Always use with the name attribute or http-equiv attribute
scheme
Use to specify the scheme to be used to translate attribute values.
CSS interview questions
What’s new with CSS3?
A:
- Added various CSS selectors (: not(.input) : all nodes whose class is not “input”)
- Rounded corner (border-radius:8px)
- Multi-column Layout
- Shadow\Reflect
- Text effects (text-shadow,)
- Text-decoration
- Linear gradient
- Transform
- Added rotation, zooming, positioning, tilting, animation, multi-background
- The transform: scale (0.85, 0.90) translate (0 px, – 30 px) skew (9 deg, 0 deg) Animation:
There are several ways to clear floats, and what are their advantages and disadvantages?
A:
- The parent div defines height
- End with an empty div tag clear:both
- The parent div defines pseudo classes :after and zoom
- The parent div defines overflow:hidden
- The parent div also floats and needs to define the width
- End with br label clear:both
- Better is the third way, many sites use this
Explain the Flexbox for CSS3?
A: after setting the Flex layout (display: Flex;) The float, clear, and vertical-align attributes of the child element are invalidated.
Elements with a Flex layout are called Flex containers, or “containers” for short.
All of its child elements automatically become container members and are called Flex items, or “items.”
The container has two axes by default: a horizontal main axis and a vertical cross axis.
The starting position of the spindle (where it intersects with the border) is called main start and the ending position is called main end; The starting position of the intersecting axis is called cross start and the ending position is called cross end.
By default, items are arranged along the main axis. The main axis space occupied by a single project is called main size, and the cross axis space occupied is called cross size.
Container properties
The following six properties are set on the container (context-content and align-items, flex-wrap:wrap is most commonly used).
-
Context-content: Defines the alignment of items on the main axis. It could take five values
- Center: a center
- Flex-start (default) : left-aligned
- Flex-end: right-aligned
- Space-between: both ends are aligned with equal intervals between items.
- Space-around: Equal spacing on both sides of each item. As a result, the spacing between items is twice as large as the spacing between items and the border.
-
Align-items: Property defines how items are aligned on the cross axis. It could take five values.
- Center: Alignment of the midpoint of the cross axis.
- Flex-start: Alignment of the starting point of the cross axes.
- Flex-end: alignment of ends of crossed axes.
- Baseline: The baseline alignment of the first line of text of the project.
- Stretch (default) : If the height is not set or auto is set, the project will occupy the entire height of the container.
-
Flex-flow: The flex-flow property is a short form of the flex-direction and flex-wrap properties. The default value is row nowrap.
-
Flex-direction: property determines the direction of the main axis (that is, the alignment of items);
- Row (default) : The main axis is horizontal and the starting point is on the left.
- Row-reverse: The main axis is horizontal and the starting point is at the right end.
- Column: The main axis is in the vertical direction, and the starting point is in the upper edge.
- Column-reverse: the main axis is vertical and the starting point is at the bottom.
-
Flex-wrap: By default, projects are arranged on a single line (aka “axis”). The flex-wrap property defines how to wrap a line if an axis does not fit.
- It could take three values.
- (1) NowRap (default) : no line breaks.
- (2) Wrap: the first line is at the top. 【 This property is often used 】
- (3) wrap-reverse: the first line is at the bottom.
-
Align-content: Property defines the alignment of multiple axes. This property has no effect if the project has only one axis
- Flex-start: align with the starting point of the cross axis.
- Flex-end: aligns with the end of the cross axis.
- Center: aligns with the midpoint of the intersecting axis.
- Space-between: aligned with both ends of the intersecting axes, with evenly distributed spacing between axes.
- Space-around: The spacing on both sides of each axis is equal. Therefore, the spacing between axes is twice as large as the spacing between axes and borders.
- Stretch (default) : Axis takes up the entire cross axis.
A summary of the project’s attributes
The following six properties are set on the project. Align -self, flex, order
-
The align – self:
- Property allows a single item to have a different alignment than other items, overriding the align-items property. The default value is auto, which inherits the align-items property of the parent element. If there is no parent element, it equals stretch. This property may take six values, all identical to the align-items property except auto.
- auto / flex-start / flex-end / center / baseline / stretch;
-
Flex:
- The property is short for flex-grow, flex-shrink, and flex-basis. The default value is 0 1 auto. The last two attributes are optional. This property has two shortcut values: auto (1 1 auto) and None (0 0 auto). It is recommended to use this attribute in preference to writing three separate attributes, as the browser will infer related values.
-
The order:
- Property defines the order in which items are sorted. The smaller the value is, the more advanced it is. The default value is 0.
-
The flex – turns up:
- Property defines the zoom scale of the project, which defaults to 0, or does not zoom if there is free space. If all projects have a flex-Grow attribute of 1, they divide the remaining space equally, if any. If one project has a flex-grow attribute of 2 and all the other projects are 1, the former takes up twice as much free space as the other items.
-
The flex – the shrink:
- The Flex-shrink attribute defines the scale by which a project shrinks. The default is 1, that is, if there is insufficient space, the project shrinks. If all projects have a Flex-shrink attribute of 1, they are scaled equally when space is insufficient. If the flex-shrink attribute is 0 for one project and 1 for all other projects, the former does not shrink when space is insufficient. Negative values have no effect on this property.
-
The flex – the basis:
- The Flex-basis property defines the main size of the project before allocating extra space. Based on this property, the browser calculates whether the main axis has extra space. Its default value is Auto, the original size of the project. It can be set to the same value as the width or height attribute (such as 350px), and the project will take up a fixed space.
Explain float and how it works? Tips for clearing floats?
A: Floating elements leave the document flow and do not take up space.
The floating element touches the border that contains it or stays in the border of the floating element
Use empty labels to clear floats
This method is to add an empty tag definition CSS clear:both. The downside is adding meaningless labels.
The use of overflow
Add CSS property overflow:auto to parent tag that contains floating elements; zoom:1; Zoom :1 is compatible with Internet Explorer 6.
How many ways can you introduce style sheet CSS? What are they? What are the priorities?
A: There are four common ways to define CSS in HTML:
- Inline (also called inline style)
- Embedding (embedded),
- Linking (external citation)
- Import the stylesheet (@import).
detailed
-
Inline/inline style: Use this property to specify the style directly. Of course, the style only applies to the content of this element, not to another element with the same name.
-
Two: embedded (style) : users can define multiple style elements in the HTML document header, to achieve multiple style sheets.
-
3. External reference
- ① Style sheets can be shared among multiple documents. For large-scale websites, CSS style definitions can be separated into a document, which can effectively improve efficiency and facilitate the maintenance of website style.
- (2) You can change the style sheet without changing the HTML document, which is consistent with the HTML language’s separation of content and form.
- ③ You can optionally load stylesheets based on the media.
-
@import URL (” CSS /base.css “);
Priority: The proximity principle
Inline > Inline > External Reference > Import style sheet
What is responsive design? What are the fundamentals of responsive design?
A: Responsive design is simply a web site that works with multiple endpoints — not a specific version for each one.
advantages
- Flexible for different resolution equipment
- It can quickly solve the problem of multi-device display adaptation
disadvantages
Compatible with a variety of equipment workload, low efficiency
Code is cumbersome, hiding useless elements, and loading times are long
In fact, this is a compromise design solution, and many factors can not achieve the best effect
Changed the original layout structure of the site to a certain extent, there will be user confusion
By following these three steps, you are sure to understand the fundamentals and media Query of responsive design.
Step 1: Meta tags
To fit the screen, most mobile browsers scale HTML pages to the width of the device’s screen. You can do this using the ViewPort property of the meta tag. The following code tells the browser to use the device screen width as the content width and ignore the initial width setting. This code is written inside
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
Copy the code
Internet Explorer 8 and later do not support Media Query. You can use media-queries.js or responder.js. This will enable IE to support Media Query.
<! - [if lt IE 9] ><script src="http://css3-mediaqueries-js.googlecode.com/svn/trunk/css3-mediaqueries.js"></script><! [endif]-->Copy the code
Step 2. HTML structure
In this example, header, Content, sidebar and footer are the basic layout of the web page.
Header has a fixed height of 180px, content container is 600px wide, and sidebar is 300px wide.
Step 3: Media Queries
CSS3 Media Query Is the key to responsive Web design. It acts like an if statement that tells the browser how to load a web page based on a specific screen width.
If the screen window is smaller than 980px, the rule takes effect. Set the width of the container as a percentage instead of pixels for more flexibility.
Change the background-color if the document width is less than 300 pixels:
@media screen and (max-width: 300px) {
body {
background-color:lightblue; }}Copy the code
What is the principle behind creating a triangle with pure CSS?
Answer: equalization principle
At the right Angle of the rectangle, the two sides should be evenly divided
For example, the border-top and border-left corner styles should be evenly split
If border-left is colorless and transparent and border-top is colored, an acute Angle of 45 degrees will appear
What about the box model?
Answer: very simple, but can say good compare difficulty, can expand, answer deeper, wider, add extra points more
Box-sizing: border-box; margin-top: 25px; margin-bottom: 25px; margin-bottom: 25px; Properties change the box model
After writing this property, the width will include border, because the mobile side is mainly used in percentage, it is impossible to control accurately by pixel, if two screen 50% divs side by side, and the two divs also have border and padding, the original box model can not do this, must use the CSS property to change it. But there’s a problem;
Font-size :0; inline: block; font-size:0; inline: block; To solve the
Two box models
Box-sizing attribute is defined in CSS3. Mobile applications;
- Short for padding and margin
- Margin two centered DIV methods; (margin: 0 auto; And negative margin.
- Margin compatibility problem, IE6img below have blank;
- New CSS3 property for border;
- Border: triangle;
Understanding of the BFC specification?
A :(a concept in the W3C CSS 2.1 specification that determines how an element locates its content and how it relates and interacts with other elements.)
BFC, block-level formatting context, a box that creates a new BFC is laid out independently, and the style of the child elements inside the box does not affect the outside elements
. Two adjacent block-level boxes in the same BFC will collapse at the vertical (relative to the layout direction) margin.
A page is made up of boxes, and the type of the Box is determined by the element type and the display attribute.
Different types of boxes are involved in different Formatting contexts, so elements inside the Box are rendered in different ways, that is, elements inside and outside the BFC do not affect each other.
Why position absolute and float affect performance?
A: Position: Absolute is completely removed from the document stream
The left, top, right, and bottom values are ancestor elements that have position: relative or position: absolute set relative to their nearest position.
If neither ancestor element has position: relative or position: Absolute set, it is relative to the body element.
Float can also change the flow of documents
Unlike position: relative and position, float does not float elements “up” to another Z-index layer. It still aligns elements at z-index:0. Absolute As such, it cannot precisely control the coordinates of elements with the left, top, right, and bottom attributes. It can only control elements “float left” and “float right” in the same layer with float:left and float:right. Float alters the normal document flow arrangement, affecting surrounding elements.
Another interesting phenomenon is that position: Absolute and float implicitly change the display type, regardless of any previous type of element (except display: None), whenever position: is set. Either absolute or float makes the element display as display:inline-block: the length and width can be set, and the default width does not fill the parent element.
Even if we display display:inline or display:block, it still doesn’t work (float’s double margin bug in IE6 is solved by adding display:inline).
Note that position: relative does not change the display type.
Elements with position attributes such as absolute or fixed have a lower rearrangement overhead because they do not have to consider their impact on other elements
This rule explains why Position: Absolute; Float elements instead of float
Why is JS down here? Why is CSS up here?
A: The browser parses the HTML document from top to bottom.
Put the CSS file in the header. The CSS file can be loaded first. Avoid loading the body content first, causing the page to start out out of shape and then flicker.
Put the javascript file at the bottom because: If
Putting a javascript file inside the head means that you have to wait until all the javascript code has been downloaded, parsed, and executed before rendering the page content.
This results in a noticeable delay in rendering the page and a blank window.
To avoid this problem, place all javascript files after the page content in the body element.
What are the problems and solutions caused by floating elements?
A:
- The height of the parent element cannot be spread out, affecting elements at the same level as the parent element
- Non-floating elements of the same class as floating elements follow
- If the first element does not float, the elements preceding it need to float as well, otherwise the structure of the page will be affected
Extra label method
<div style="clear:both;"></div>
Copy the code
Cons: This method, however, adds extra tags and makes the HTML structure look less concise.
Use the after pseudo-element
#parent:after{
content : ".";
height : 0;
visibility : hidden;
display : block;
clear : both;
}
Copy the code
The parent element also sets the float
Disadvantages: The layout of elements adjacent to the parent element is affected and cannot float all the way to the body. Not recommended
Set Overflow to Hidden or Auto
Summary of CSS browser compatibility problems:
A: Browser compatibility refers to the situation where different browsers parse the same code differently, resulting in different page displays.
In most cases, our requirement is that no matter what browser the user uses to view our site or log in to our system, the display should be uniform.
Aside from bugs in IE6 and 7, there are few bugs in other browsers. If you understand the meaning of every CSS sentence and write code in a standard way, there will be very few bugs.
As a simple example, many people are worried about the double margin bug in IE6 after float:left. This is actually wrong. You need to understand how the double margin bug in IE6 occurs:
This bug occurs when the floating direction has a margin value in the same direction. So if you just float, you won’t get this bug.
Browser compatibility problem 1: Labels of different browsers have different external and internal patches by default
Symptom: The margin and padding of several labels are different without style control.
*{margin:0; padding:0; }
Note: This is one of the most common and easiest browser compatibility issues to solve. Almost all CSS files start with the wildcard * to set the internal and external patches of each label to 0.
Browser compatibility problem 2: After the block property tag float, there is a horizontal margin case, in IE6 display margin larger than the set
Symptom: A common symptom is that the last block in IE6 is pushed to the next line
Frequency of encounters: 90% (slightly more complex pages, most common browser compatibility issues with float layouts)
Solution: Add display:inline; Convert it to an inline property
Note: The most commonly used layout is div+CSS, and div is a typical block attribute tag. Horizontal layout is usually implemented with div float, and horizontal spacing is implemented with margin, which is an inevitable compatibility problem.
Browser compatibility problem three: set a small height label (generally less than 10px), in IE6, IE7, roaming height beyond their own Settings
Symptom: Internet Explorer 6, 7 and Surf this TAB height is out of control, beyond their own setting height
Frequency of encounter: 60%
Solution: Set overflow: Hidden for tags out of height; Or set the line height to be less than the height you set.
Note: this is usually the case with labels with small rounded backgrounds. The reason for this is that browsers prior to IE8 gave tags a minimum default line height.
Even if your label is empty, the label will still be the default line height.
Browser compatibility problem 4: Inline property tags, display:block after float layout, and horizontal margin situation, IE6 spacing bug
Symptom: The spacing ratio in IE6 exceeds the set spacing
Chance of encounter: 20%
Solution: display:block; Add display:inline; display:table;
Note: Inline property tags. To set the width and height, we need to set display:block; (Except for the input tag).
After a float layout with a horizontal margin, in IE6 it had a bug with the horizontal margin after the block property float.
But since it is an inline attribute tag, we add display:inline, and its width and height are not set. We also need to add display:talbe after display:inline.
Browser compatibility problem 5: Images are spaced by default
Symptom: Some browsers have a default spacing when several IMG tags are placed together, and the wildcards mentioned in Problem 1 do not work.
Chance of encounter: 20%
Solution: Use the float property for the IMG layout
Note: Since the IMG tag is an inline attribute tag, the IMG tag will be placed on a line as long as it is within the width of the container, but some browsers will have a space between the IMG tags.
Remove that spacing and use float is the way to go. (One of my students uses negative margin, which is a browser compatibility problem, so I forbid them to use it.)
Browser compatibility Problem 6: Min-height is incompatible with the minimum label height
Symptom: Because minheight is an incompatible CSS property, setting minheight does not work well across browsers
Chance of encounter: 5%
Solution: If we want to set a minimum label height of 200px, we need to set it to: {min-height:200px; height:auto ! important; height:200px; overflow:visible; }
Note: in the front end of B/S system, there are many cases where we have this requirement. When the content is less than a value (such as 300px).
The height of the container is 300px; When the content height is greater than this value, the container height is pushed up instead of scrolling. This is where we face this compatibility issue.
Browser compatibility issue 7: Transparency is compatible with CSS Settings
The way to make compatible pages is that every time we write a small piece of code (a line or a block of layout) we have to check whether it is compatible in different browsers.
Recommended for beginners who often encounter compatibility issues. Many of the compatibility problems are caused by the way browsers parse the default attributes of tags differently, and can be easily solved with a little bit of setup.
If we are familiar with the default attributes of tags, we will have a good understanding of why compatibility problems occur and how to resolve them.
/* CSS hack*/ I rarely use hacker. I don’t like to write code that is incompatible with IE and then hack it.
But hacker is pretty handy. Using Hacker, I can divide browsers into three categories: IE6; IE7 and Surf; Others (IE8, Chrome, FF, Safari, Opera, etc)
Internet Explorer 6 recognizes hackers as underscore _ and asterisk *
Internet Explorer 7 knows hacker by the asterisk *
For example, a CSS setting like this:
height:300px; *height:200px; _height:100px; IE6 reads height:300px as 300px;
Read on, it also knows *heihgt, so when IE6 reads *height:200px, it overwrites the previous conflict setting and thinks the height is 200px.
Reading on, IE6 also knows _height, so it overwrites the 200px setting and sets the height to 100px.
IE7 and Surf are the same and read down from a height of 300px.
They stop when they get to *height200px because they don’t know _height. So they parse the height to 200px, and the rest of the browser only knows the first height:300px; So they’ll parse the height to 300px.
The order of writing is important because conflicting attributes of the same priority override the previous one.
How to make Chrome support text smaller than 12px?
A:
html.body{-webkit-text-size-adjust: none; }Copy the code
The new version of Chrome has been cancelled;
CSS3 has a new property transform, and we’re using transform:scale()
p{font-size:10px; -webkit-transform:scale(0.8); }Copy the code
But, if, this property will scale the whole property of P. What if I had a background? Do I have borders? Will be shrunk!
So let’s change the structure to be
<p><span>I'm a font less than 12PX</span></p>
Copy the code
The following code
body.p{ margin:0; padding:0}
p{font-size:10px; }span{-webkit-transform:scale(0.8); display:inline-block}
Copy the code
Define display:inline-block instead of display:block; Will be found.
There will be margins. Looks like margin or padding.
That’s the problem with scaling. The original position still takes up 12px font size.
Therefore, it is necessary to modify margin accordingly. Let’s define it as negative.
There is another way to share with others online;
html {font-size: 625%; }body {font-size: 0.16 rem; }Copy the code
JavaScript interview questions
How many data types are there in JavaScript?
A: Data types can be divided into basic data types and reference data types
Basic data types: String, Number, Boolean, Null, Undefined, Symbol, BigInt;
Reference data type: Object;
Typeof can be used to detect function, and function is a special class.
Symbol and BigInt are the new data types
What do JavaScript [] and {} represent?
Answer: [] stands for array,
{} represents the object,
Both declarations are literal.
In addition to the literal approach, new Array and New Object can also be instantiated.
What is a global variable in JavaScript? What is a local variable? How is it defined?
A: Global variable is a variable defined outside the function. In JS, the global variable belongs to the Window object and its scope is the whole source program. Global variables are stored in static storage area.
A local variable is a variable that can be accessed in a particular procedure or function. It has a small scope and is released when the function finishes running.
Local variables are not explicitly defined in JavaScript, but are described relative to other programming languages.
See JavaScript Advanced Programming for global variables and function variables.
What is reserved word? What should we pay attention to when defining variables?
Reserved words are words that have already been defined in JavaScript. Some reserved words may not be used in the current syntax due to extensibility concerns. This is the difference between reserved words and keywords.
For example, class and abstract are reserved words. When defining variables, avoid having the same names as reserved words;
How do you comment HTML code, CSS code, and JS code?
A: HTML comment syntax
<! -- Comment content -->
Copy the code
CSS Comment syntax
/* Comment the content */Copy the code
JavaScript comments
/* * * */Copy the code
Write a timer that cycles from 0 to 59?
A:
var flag = 0;
function timer () {
flag++;
if (flag > 59) {
flag = 0;
return;
}
console.log(flag);
}
setInterval(timer, 1000);
Copy the code
JavaScript event bubble mechanism?
A: Event propagation mechanism (whether DOM0 or DOM2, this mechanism is inherent);
When an event behavior of the underlying element is triggered, the corresponding event behavior of its parent element is also triggered, all the way up to our document; (Only the same event type is triggered)
The mechanism that propagates from the bottom level up is called bubbling;
Dom2-level binding event, the third parameter false represents the bubble phase execution, if true, represents the capture phase execution;
The same element can be processed in either the capture phase or the bubble phase;
DOM0 level can basically control the bubble stage, while DOM2 level can control the capture stage.
Event delegation
Using THE DOM propagation mechanism (click on any element, the Document click must start), we bind the document to a click event, in the event we only need to get the event source; It is possible to do different events according to different event sources (so that you do not have to bind events to elements).
When an event occurs in a child element, it causes a chain reaction, even on its ancestor element. For example, if you click on a div, you click on a body, you click on an HTML, you click on a Document;
There are two things to consider when understanding event propagation;
One is that the event itself propagates, not the methods bound to the event.
Onfocus, onblur, onMouseEnter and onMouseleave are not propagated.
We need to know what the common event default behavior is, and we need to know how to organize the default behavior by saying return false at the end of the method bound to the event;
However, it is important to note that if your event binding is implemented using addEventListener, the organization default behavior must be e.preventDefault=true;
Prevents events from bubbling
function (e) {
e.preventDefault();
}
Copy the code
Event delegate: Event delegate is to use the event propagation mechanism, no matter which page element, its click event will eventually be transmitted to the Document, so that the document only need to process the click event;
document.onclick=function(e){
e=e||window.event;
var target=e.targrt||e.srcElement;// Getting the event source is the key;
alert(target.nodeName);
return false;
}
Copy the code
The key of event delegation is to understand the concept of event source.
What are the JavaScript event compatibility issues? How to solve it?
The event object itself, standard browsers automatically pass an argument to the method when the time occurs, this argument is the time object, IE is the global window.event; (the solution is: e = e | | window. The event)
2, event source: E.target, IE is e.scrcElement; (the solution is var target = e. arget | | e.s rcElement;)
3, DOM level 2 event binding: ele.addEventListener,IE is ele.attachEvent;
The solution is through
if(ele.addEventListener){
}else if(ele.attachEvent){
}
Copy the code
The corresponding removal methods to resolve the binding are removeEventListener and IE detachEvent;
4, in the third point of IE attachEvent binding method,
-
First, this is not the current element, but the window;
-
Second, the sequence of events is out of order;
- In IE678, if there are less than nine bound methods, the order of execution is reversed. If there are more than nine bound methods, execution is chaotic.
-
Third, the same function can be repeatedly bound to the same event;
- A function should not be bound to the same event twice. This rule is not followed in earlier versions of IE. Ensure that a method can only be bound to an event once;
5. Prevent the event from spreading; E.toppropagation,IE is e.ancelbubble =true. You don’t have to do anything with this, you can do observer mode with this property;
6, prevent default behavior: e.preventDefault() method, IE is e.turnValue =false;
7, e.p ageX, e.p ageY excuse; The mouse coordinates relative to the document are not supported by IE; But they all support clentX, clentY, and this is the mouse coordinates relative to the browser. This can be done by scrollTop+clientY; i.
e.pageX=(document.documentElement.scrollLeft||document.body.scrollLeft)+ e.clientX;
e.pageY=(document.documentElement.scrollTop||document.body.scrollTop)+ e.clientY;
Copy the code
JavaScript DOM how to create elements, add elements, move elements, copy nodes, delete, replace elements, find nodes?
A: Create elements
document.createElement('tagName');
Copy the code
Add elements
parent.appendChild(childNode);
Copy the code
Note: The parent element calls this method
Mobile elements
Since the DOM object is a reference type, when the appendChild and insertBefore methods are used,
The controlling node, if it is a node that exists in the document, is moved to the target.
Copy the node
oLi.cloneNode(true);
Copy the code
Note: Parameter true indicates deep clone (deep copy), false indicates shallow clone (shallow copy), deep copy is the number of replicated nodes and the whole node. Shallow copy Replicates the node itself. The copied copy of the returned node is owned by the document, but no parent node is specified for it. Thus, the entire node copy becomes an orphan:
<ul id='oUl'>
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
<ul>
<script>
var myList = document.getElementById("oUl");
var deepList = myList.cloneNode(true);
console.log(deepList.childNodes.length);//3 (IE<9) or 7 (other browsers)
var shallowList = myList.cloneNode(false);
console.log(shallowList.childNodes.length);/ / 0
</script>
Copy the code
Note that childNode contains text nodes.
The cloneNode() method does not copy JS properties that add DOM nodes, such as event handlers, etc. This method copies only features and nothing else.
Remove nodes
parentNode.removeChild(childNode);
Copy the code
Note: The parent element calls this method and returns the deleted node
Replace the element
parentNode.replaceChild(newNode,oldNode);
Copy the code
Note: oldNode must be a child of parentNode.
Insert elements
parentNode.insertBefore(newEle, oldNode);
Copy the code
Note: The parent element calls this method
Find the summary of the node
- ChildNodes – returns a node list of nodes to childNodes
- FirstChild – returns the firstChild of the node;
- LastChild – returns the lastChild of the node;
- NextSibling – returns the sibling node immediately after the node;
- NodeName – Returns the name of the node, according to its type;
- NodeType – Returns the type of the node;
- NodeValue – Sets or returns the value of a node, based on its type;
- OwnerDocument – Returns the root element of the node (the Document object);
- ParentNode – returns the parentNode of the node;
- PreviousSibling – returns the sibling node immediately before the node;
- Text – returns the text of the node and its descendants (IE only);
- XML – XML that returns nodes and their descendants (IE only);
Method of a node object
- AppendChild () – adds a new child node to the end of the node’s child node list;
- CloneNode () — Copy node;
- HasChildNodes () – Determines whether the current node has children;
- InsertBefore () – Inserts a new child before the specified child;
- Normalize () – Merges adjacent Text nodes and removes empty Text nodes;
- RemoveChild () – Removes (and returns) the specified children of the current node;
- ReplaceChild () – replaces a child node with a new node;
IE6 unique method
- SelectNodes () – Queries selected nodes with an XPath expression;
- SelectSingleNode () – finds a node that matches an XPath query;
- TransformNode () – Transforms a node into a string using XSLT. TransformNodeToObject () – Transforms a node into a document using XSLT.
Classic problem solving
Creating a New node
- CreateDocumentFragment () // Create a DOM fragment
- CreateElement () // Create a specific element
- CreateTextNode () // Create a text node
Add, remove, replace, insert
- appendChild()
- removeChild()
- replaceChild()
- InsertBefore () // Inserts a new child before an existing one
To find the
- GetElementsByTagName () // Pass the tag name
- GetElementsByName () // Pass the value of the element’s Name attribute.
- GetElementById () // Unique by element Id
How is your DOM encapsulated? How are the various libraries written? DOM library,AJAX library, animation library, event library?
A: when the scope covers the scope; A subscope should not return a reference data type, because if the value inside the closure is the return value of another child closure, if the return value of the child closure is a literal, then the browser will destroy the scope at idle time. If the value returned is a reference to a data type, the closure will not be destroyed.
Here’s the encapsulation idea;
var Tool = function () {// Constructor mode; You need to refresh it when you use it;
this.flag = "getElementsByClassName" in document;
//getElementsByClassName does not exist in IE678. Use this to determine if it's a lower version of Internet Explorer;
// Check whether this. Flag exists; If it exists it's standard, if it doesn't it's IE;
};
Tool.prototype = {// The method is defined on the prototype of Tool;
constructor: Tool,// Prototype constructor is not the original Tool; Need to manually force him to write to the Tool;
getIndex: function () {},// Simple remarks;
toJSON:function(){},// Simple remarks;
likeArray:function(){}// Simple remarks;
}
Copy the code
Common methods for JavaScript strings?
A:
- CharAt gets the character at the specified index position
- CharCodeAt Retrieves the ASCII code value of the character at the specified index position
- Indeof /lasrIndexof returns the index of the first (and last) occurrence of a string, or -1 if not. This is used to check whether a string contains a character.
- ToUpperCase/tolowerCase turn capital | lowercase letters from a string;
- Split according to the specified delimiter, a string split into an array, and the array corresponding to the join;
- Substr: substr(n,m) takes m characters from index n and returns a new string.
- Substring: substring(n,m) cuts from index n to index M (excluding m) and returns the found character as a new string.
- Slice: The usage of slice(n, m) is the same as that of substring, except that slice supports a negative index. When a negative index is present, the length of the string + the negative index is used. Ary. Slice (ary. Length-6,ary. Length-2)
- The above three methods, if you write only one n, are all truncated to the end of the string by default;
- Replace: Replace (” old characters to be replaced “, “new characters to be replaced”) string character replacement method, can use the re to uniformly Replace, in the re we will explain in detail the powerful application of Replace;
- Match: Capture all matches with the re (not small groups)
- Trim: Remove trailing whitespace from a string (incompatible)
When submitting the form, the input field must not be empty. If there is any space, it must be removed. It must be a valid mobile phone number.
A:
<form action="" id="form1" method="get">Telephone No. :<input type="text" value="Enter a phone number" id="mobi" name=""/>
<input type="submit" name=""/>
</form>
Copy the code
var form1 = document.getElementById('form1');
form1.onsubmit = function () {
var mobi = document.getElementById('mobi');
var reg = /^1\d{10}$/;
if (reg.test(mobi.value.replace(/ /g.' '))) {
console.log('ok');
} else {
console.log('error');
return false; }}Copy the code
Explain JavaScript’s same-origin policy?
A: Concept: The same-origin policy is an important security metric for client-side scripts, especially Javascript.
It originated in Netscape Navigator2.0 to prevent a document or script from being loaded from multiple sources.
The same origin policy means that the protocol, domain name, and port are the same.
The same origin policy is a security protocol: a script can only read the properties of Windows and documents from the same source.
How does JavaScript AJAX work?
A: Ajax is a collection of many technologies. including
The browser’s xmlHTTPRequest object, which is responsible for opening another connection channel for you, can pass information.
Javascript: This is the medium responsible for calling the XMLHTTPRequest object to interact with the background.
XML is a data format used by the server to respond to passing information. In addition to XML, you can use any text format, including text, HTML, JSON, and so on.
Ajax is not a new technology, but rather a combination of several existing technologies. It is a combination of the following technologies.
- Use CSS and XHTML.
- Use DOM models for interaction and dynamic display.
- Use XMLHttpRequest to communicate asynchronously with the server.
- Use javascript to bind and call.
All of the technologies above, with the exception of the XmlHttpRequest object, are based on web standards and are already widely used. XmlHttpRequest has not yet been adopted by the W3C, but it is already a de facto standard. It is supported by almost all major browsers today.
XMLHttpRequest is the core mechanism of Ajax. It was first introduced in IE5 and is a technology that supports asynchronous requests. In simple terms, javascript can make requests to the server and process responses in a timely manner without blocking the user. Achieve no refresh effect.
So let’s start with XMLHttpRequest and see how it works.
The properties of the XMLHttpRequest
Its properties are:
-
Onreadystatechange Event handler for the event triggered by each statechange.
-
ResponseText Is a string of data returned from the server process.
-
ResponseXML The DOM compatible document data object returned from the server process.
-
Status Numeric codes returned from the server, such as the common 404 (not found) and 200 (ready)
-
Status Text Indicates the character string accompanying the status code
-
ReadyState Object state value
0
(uninitialized) Object created but not initialized (the open method has not been called)1
The object has been created and the send method has not been called2
The send method was called, but the current state and HTTP header are unknown3
[error] Select responseBody, responseText from responseBody; [error] select responseBody, responseText from responseBody; [error] select responseText from responseBody; [error] select responseText from responseBody;4
ResponseXml and responseText are available to retrieve the complete response data
However, because of differences between browsers, creating an XMLHttpRequest object may require different methods.
This difference is mainly between Internet Explorer and other browsers. Here is a more standard way to create an XMLHttpRequest object.
function CreateXmlHttp () {
// Create an XmlHttpRequest object in a non-Ie browser
if (window.XmlHttpRequest) {
xmlhttp = new XmlHttpRequest();
}
// Internet Explorer creates an XmlHttpRequest object
if (window.ActiveXObject) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
try {
xmlhttp = new ActiveXObject("msxml2.XMLHTTP");
}
catch (ex) { }
}
}
}
function Ustbwuyi () {
var data = document.getElementById("username").value;
CreateXmlHttp();
if(! xmlhttp) { alert("XMLHTTP object creation exception!");
return false;
}
xmlhttp.open("POST", url, false);
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
document.getElementById("user1").innerHTML = "Data is loading...";
if (xmlhttp.status == 200) {
document.write(xmlhttp.responseText);
}
}
}
xmlhttp.send();
}
Copy the code
As shown above, the function first checks the overall state of the XMLHttpRequest and guarantees that it has completed (readyStatus=4), that is, the data has been sent.
The server then asks for the status of the request, and if everything is ready (status=200), do the following.
For XmlHttpRequest’s two methods, open and send, the open method specifies:
- A. The type of data submitted to the server, i.e. Post or GET.
- B. Requested URL and passed parameters.
- C. Transmission mode: False: synchronous; true: asynchronous. The default is true. If it is asynchronous (true), the client does not wait for a response from the server. In synchronous mode (False), the client waits until the server returns the message before performing any other operations. We need to specify the synchronization mode according to actual needs. In some pages, multiple requests may be sent, or even large-scale and high-intensity requests may be organized, planned and formed, and the latter one will overwrite the previous one, so of course we need to specify the synchronization mode.
The Send method is used to Send a request
Given the workflow of XMLHttpRequest, you can see that XMLHttpRequest is all about making a request to the server, and it doesn’t do much more than that, but its role is central to the entire Ajax implementation, because Ajax is just two processes, making a request and responding to a request.
And it’s totally a client-side technology. It’s XMLHttpRequest that handles server-side and client-side communication that makes it so important.
Now you have a pretty good idea of how Ajax works. We can think of the server side as a data interface that returns a stream of plain text, of course, in XML format, Html, Javascript code, or just a string.
At this point, XMLHttpRequest requests the page to the server, and the server writes the result of the text to the page. This is the same as a normal Web development process, except that the client asynchronously obtains the result, which is not directly displayed on the page, but is processed by javascript, and then displayed on the page. Many popular Ajax controls, such as MagicAjax, can return other data types, such as DataSet, but encapsulate the result of the process, essentially they are not much different.
What are HTTP status codes? What do they stand for?
A:
- 100-199 Indicates the actions that the client should take.
- 200-299 Indicates that the request is successful.
- 300-399 Is used for files that have been moved and is often included in the location header to specify new address information.
- 400-499 Indicates errors on the client. The current request cannot be understood by the server. 401 The current request requires the user to verify that the 403 server understands the request but refuses to execute it.
- 500-599 is used to support server errors. 503 — Service unavailable;
The commonly used
- 100 Continue When a POST request is sent, the server sends an acknowledgement message after the HTTP header has been sent, and then sends specific parameter information
- 200 OK A normal message is displayed
- 201 Created The request succeeds and the server creates a new resource
- 202 Accepted the request has been Accepted but not yet processed
- 301 Moved Permanently The page for the Permanently Moved Permanently to the new location.
- 302 Found Temporary redirect.
- 303 See Other Temporary redirects and always uses GET to request new URIs.
- The requested page has Not been Modified since the last request.
- 400 The Bad Request server cannot understand the format of the Request. The client should not attempt to use the same content to initiate a Request again.
- 401 Unauthorized The request is not authorized.
- 403 Forbidden Forbidden access.
- 404 Not Found The resource how to match the URI was Not Found.
- 500 Internal Server Error Common Server errors.
- 503 Service Unavailable The server cannot process the request temporarily (possibly due to overload or maintenance).
A page enters a URL to the page load display is complete, what happens in between?
A:
-
Enter the URL in the browser address bar
-
The browser checks the cache, and if the requested resource is in the cache and fresh, skip to the transcoding step
-
If the resource is not cached, make a new request
-
If it is cached, check whether it is fresh enough and provide it to the client directly. Otherwise, check with the server.
-
Checking freshness usually has two HTTP headers for controlling Expires and cache-control:
- HTTP1.0 provides Expires, with a value of an absolute time to indicate a cached fresh date
- HTTP1.1 added cache-control: max-age=, which is the maximum fresh time in seconds
-
-
Browser parse URL fetch protocol, host, port, path
-
The browser assembles an HTTP (GET) request packet
-
The browser obtains the host IP address as follows:
- Browser cache
- This machine is the cache
- Hosts file
- Router cache
- ISP DNS cache
- DNS recursive query (different IP addresses may occur due to load balancing)
-
Open a socket with the destination IP address, establish a TCP connection with the port, and shake hands three times as follows:
- The client sends a TCP SYN=1, Seq=X packet to the server port
- The server sends back a response packet with SYN=1, ACK=X+1, Seq=Y
- The client sends ACK=Y+1, Seq=Z
-
After a TCP connection is established, an HTTP request is sent
-
The server accepts the request, parses it, and forwards the request to the server, such as the virtual Host using the HTTP Host header to determine the requested server
-
The server checks whether the HTTP request header contains cache authentication information. If the cache is fresh, the server returns the status code, such as 304
-
The handler reads the complete request and prepares the HTTP response, which may require, for example, querying the database
-
The server sends the response back to the browser over the TCP connection
-
The browser receives the HTTP response and then closes the TCP connection or retains the TCP connection for reuse. The four-way handshake for closing the TCP connection is as follows:
- The active party sent Fin=1, Ack=Z, Seq= X packets
- The passive sends ACK=X+1, Seq=Z packets
- The passive sends Fin=1, ACK=X, and Seq=Y packets
- The active party sends ACK=Y, Seq=X packets
-
Does the browser check the response status: 1XX, 3XX, 4XX, 5XX, these cases are handled differently from 2XX
-
If the resource is cacheable, cache it
-
Decode the response (for example, gzip compression)
-
Decide what to do based on the resource type (assuming the resource is an HTML document)
-
Parsing HTML documents, building DOM trees, downloading resources, constructing CSSOM trees, and executing JS scripts are all in no strict order, as explained below
-
Build a DOM tree:
- Tokenizing: Parsing character streams into tags according to the HTML specification
- Lexing: Lexical analysis converts tags into objects and defines attributes and rules
- DOM Construction: Organize objects into DOM trees based on HTML tag relationships
-
Image, style sheet, JS file encountered during parsing, start download
-
Build the CSSOM tree:
- Tokenizing: Character stream converted to token stream
- Node: Creates a Node based on the tag
- CSSOM: The node creates the CSSOM tree
-
Build render tree from DOM tree and CSSOM tree:
- All visible nodes are traversed from the root node of the DOM tree. Invisible nodes include: 1) script, meta and other tags that are not themselves visible. 2) Nodes hidden by CSS, such as display: None
- For each visible node, find the appropriate CSSOM rule and apply it
- Publish the content and calculation style of the visual node
-
Js parsing is as follows:
- The browser creates the Document object and parses the HTML, adding parsed elements and text nodes to the Document. Document. readystate is loaded
- When the HTML parser encounters scripts without async and defer, it adds them to the document and then executes inline or external scripts. These scripts execute synchronously, and the parser pauses while the script is downloaded and executed. This allows you to insert text into the input stream with document.write(). Synchronous scripts often simply define functions and register event handlers that can iterate and manipulate scripts and their previous document contents
- When the parser encounters a script with the async property set, it starts downloading the script and continues parsing the document. The script is executed as soon as it is downloaded, but the parser does not stop for it to download. Document.write () is prohibited for asynchronous scripts, which have access to their own script and previous document elements
- When the document is parsed, document.readState becomes interactive
- All defer scripts will be executed in the order in which they appear in the document. The deferred script has access to the full document tree, and document.write() is prohibited.
- The browser fires the DOMContentLoaded event on the Document object
- When the document is fully parsed, the browser may still be waiting for content such as images to load. When that content is loaded and all asynchronous scripts are loaded and executed, document.readState changes to complete and the window fires the load event
-
Display the page (the page is displayed gradually as the HTML is parsed)
Asynchronous and lazy loading?
A:
- Asynchronous loading scheme: dynamic insert script tag
- Get the JS code through Ajax and execute it through eval
- Add defer or async properties to the script tag
- Create and insert an iframe to execute JS asynchronously
- Lazy loading: Some JS code is not required immediately when the page is initialized, but later in some cases.
Understanding of website refactoring? How do I refactor the page?
A: How do I refactor the page?
Write CSS, make the page structure more reasonable, improve user experience, achieve good page effect and improve performance.
Understanding of website refactoring
Site refactoring: The act of simplifying structure and adding readability while maintaining consistency at the front end of a site without changing external behavior. The idea is to optimize the site without changing the UI, and maintain a consistent UI while extending it.
For traditional websites refactoring is usually
- Table layout changed to DIV+CSS
- Make the front end of the site compatible with modern browsers (against substandard CSS, such as IE6)
- Optimization for mobile platforms
- Optimize for SEO
- Deep site refactoring should be considered
- Reduce coupling between codes
- Keep your code elastic
- Code strictly to specifications
- Design extensible apis
- Replace old frameworks and languages (e.g. VB)
- Enhance the user experience
- Optimizations for speed are often included in refactoring
- Compress JS, CSS, image and other front-end resources (usually handled by the server)
- Application performance optimization (such as data read and write)
- CDN is used to accelerate resource loading
- Optimization of JS DOM
- HTTP server file cache
What exactly does the JavaScript new operator do?
A:
- Creates an empty object, and the this variable references the object and inherits the prototype of the function
- Properties and methods are added to the object referenced by this
- The newly created object is referred to by this and implicitly returns this
var obj = {};
obj.__proto__ = Base.prototype;
Base.call(obj);
Copy the code
What does JavaScript call and apply() do?
Answer: the core
To dynamically change the runtime environment of a method on a class is to change the this keyword
- Call is passing arguments one by one
- Use apply to pass parameters as data, similar to arguments;
The difference between call and apply
- Function.prototype.call and function.prototype. apply work the same way; the only difference is the form of the parameters passed in.
- When using Call or Apply, if the first argument we pass in is NULL, this in the function body refers to the default host object, and window in the browser
- Sometimes we use call or apply not to refer to this, but for other purposes, such as borrowing methods from other objects. We can then pass null in place of a specific object
Use of call and apply
- Change the direction of this
- Function.prototype.bind
- Borrowing methods from other objects
call
function add (a, b) {
console.log(a + b);
}
function sub (a, b) {
console.log(a - b);
}
add.call(sub, 3.1);
// replace sub with add, add. Call (sub,3,1) == add(3,1);
Copy the code
Functions in js are actually objects, and Function names are references to Function objects
JavaScript: What about this object?
A:
this
Refers to the object on which the function is calledthis
You can’t know who you represent until you run it; jsthis
Pointing is indeterminate; It’s not about definition, it’s about implementation,- When I do that, I click who’s in front of me,
this
Who is; Inside the self-executing functionthis
Represents thewindow
- When the timer is written, the window can be omitted. When the timer went off, the inside
this
It also representswindow
; this
Is a keyword of js, depending on where the function is used,this
The value of theta will change.
JavaScript what is a Window object? What is a Document object? Say what you understand
A:
-
Document is an object property of the window.
-
The window object represents the window open in the browser.
-
If the document contains frames (frame or iframe tags), the browser creates a Window object for the HTML document and an additional Window object for each frame.
-
All global functions and objects belong to properties and methods of the Window object.
- For example, you can just write document instead of window.document.
- Similarly, you can use the methods of the current Window object as functions, such as alert() instead of window.alert ().
-
Document a read-only reference to the document object.
How many ways can Javascript create objects?
A:
- The factory pattern
- Constructor pattern
- The prototype pattern
- Mix constructors and stereotype patterns
- Dynamic prototype pattern
- Parasitic constructor pattern
- Secure constructor pattern
Javascript object creation is simply a matter of using built-in objects or various custom objects. You can also use JSON; But there are many ways to write it. It can also be mixed.
1. The way objects are literal
person={
firstname:"zhu".lastname:"anbang".age:25.eyecolor:"black"};
Copy the code
2. Use function to simulate a parameterless constructor
function Person(){}
var person=new Person();// Define a function. If "instantiated" with new, the function can be considered a Class
person.name="zhu";
person.age="25";
person.work=function(){
alert(person.name+" hello...");
}
person.work();
Copy the code
Use function to simulate the parameter constructor (use this keyword to define the context of the constructor).
function Pet(name,age,hobby){
this.name=name;// This scope: current object
this.age=age;
this.hobby=hobby;
this.eat=function(){
alert("My name is"+this.name+"I like it."+this.hobby+"He's a programmer."); }}var maidou =new Pet("McDull".25."coding");// instantiate and create objects
maidou.eat();// Call the eat method
Copy the code
4. Create (built-in objects) in factory mode
var wcDog =new Object(a); wcDog.name="Prosperous wealth.";
wcDog.age=3;
wcDog.work=function(){
alert("I am"+wcDog.name+", woof woof......");
}
wcDog.work();
Copy the code
5. Prototype
function Dog(){}
Dog.prototype.name="Prosperous wealth.";
Dog.prototype.eat=function(){
alert(this.name+"A foodie.");
}
var wangcai =new Dog();
wangcai.eat();
Copy the code
5. Create a hybrid
function Car(name,price){
this.name=name;
this.price=price;
}
Car.prototype.sell=function(){
alert("I am"+this.name+". I'm selling now."+this.price+"Ten thousand dollars");
}
var camry =new Car(Camry.27);
camry.sell();
Copy the code
How to do JavaScript modular development?
A: Core: Execute functions immediately without exposing private members
var module1 = (function () {
var _count = 0;
var m1 = function () {
/ /...
};
var m2 = function () {
/ /..
};
return {
m1: m1,
m2: m2 }; }) ();Copy the code
Var ary=[1,2,3,5,7,90,3,6];
Answer: alert (Math. Max. Apply (null, a)).
Pass a as an argument and return the sorted array. The first argument is null because there is no need to borrow an object and this value can be ignored.
var a = [3.4.6.2.9.11.4];
var maxNum = Math.max.apply(null, a);
console.log(maxNum);/ / 11
Copy the code
Note: a is passed in as an argument, and since the calling object is negligible, the first argument is null,Copy the code
Math.max.apply returns a new value.
The other way is, sort first, and then the heads and tails are what we want;
ary.sort(function(a,b){return a-b})
console.log(ary[0]);
console.log(ary[ary.length-1]);
Copy the code
Js object deep clone?
A:
function clone (Obj) {
var buf;
if (Obj instanceof Array) {
buf = []; // Create an empty array
var i = Obj.length;
while (i--) {
buf[i] = clone(Obj[i]);
}
return buf;
} else if (Obj instanceof Object) {
buf = {}; // Create an empty object
for (var k in Obj) { // Add new attributes to this object
buf[k] = clone(Obj[k]);
}
return buf;
} else {
returnObj; }}Copy the code
Network communication interview questions
HTTP status code and its meaning?
A:
-
1XX: indicates the information status code
- 100 Continue Indicates that the server has sent the HTTP header before sending a POST request
- This message is returned, indicating confirmation, and the specific parameter information is sent
-
2XX: success status code
- 200 OK A normal message is displayed
- 201 Created The request succeeds and the server creates a new resource
- 202 Accepted the request has been Accepted but not yet processed
-
3XX: redirection
- 301 Moved Permanently The page for the Permanently Moved Permanently to the new location.
- 302 Found Temporary redirect.
- 303 See Other Temporary redirects and always uses GET to request new URIs.
- The requested page has Not been Modified since the last request.
-
4XX: Client error
- 400 The Bad Request server cannot understand the format of the Request. The client should not try to use the same format again
- Allow to initiate a request.
- 401 Unauthorized The request is not authorized.
- 403 Forbidden Forbidden access.
- 404 Not Found The resource how to match the URI was Not Found.
-
5XX: Server error
- 500 Internal Server Error Common Server errors.
- 503 Service Unavailable The server cannot process the request temporarily (possibly due to overload or maintenance).
How many HTTP request methods are used?
A:
The GET method
- Sends a request to retrieve a resource on the server
POST method
- Submits data or appends new data to the resource specified by the URL
PUT method
- Much like the POST method, it wants to submit data to the server. But there are differences. PUT specifies the location of the resource on the server, whereas POST does not
The HEAD method
- Only the header of the page is requested
The DELETE method
- Example Delete a resource on the server
The OPTIONS method
- It is used to get the methods supported by the current URL. If the request is successful, there is an Allow header that contains information like “GET,POST”
The TRACE method
- The TRACE method is used to fire a remote, application-level request message loop
The CONNECT method
- Convert the request connection to a transparent TCP/IP channel
What about websockets?
A: Because there is an obvious drawback of HTTP (messages can only be pushed to the server by the client, and the server cannot actively push messages to the client), so if the server has continuous changes, only polling can be used, and polling is too inefficient and not suitable. So WebSocket was invented
Compared to HTTP, it has the following advantages
- Support two-way communication, more real-time;
- You can send text or binary files;
- The protocol identifier is WS and WSS after encryption.
- Less control overhead. After the connection is created, when the WS client and server exchange data, the packet header controlled by the protocol is small. Without the header, the client-to-client header is only 2 to 10 bytes (depending on the packet length), with an additional 4-byte mask for client-to-server. HTTP requires a complete header for each communication.
- Support for extensions. The WS protocol defines extensions, and users can extend the protocol or implement custom subprotocols. (such as
- With custom compression algorithm, etc.)
- No cross-domain problems.
Implementation is relatively simple, server libraries such as socket. IO, WS, can help us get started.
The client only needs to follow the API implementation
What is the difference between Ajax, Axios and FETCH?
A: the jQuery ajax
$.ajax({
type: 'POST'.url: url,
data: data,
dataType: dataType,
success: function () {},
error: function () {}});Copy the code
The advantages and disadvantages:
- Itself is for MVC programming, not in line with the current wave of front-end MVVM
- Based on native XHR development, the architecture of XHR itself is not clear, and there is an alternative to FETCH
- The entire JQuery project is too big, and using Ajax alone to introduce the entire JQuery is very unreasonable (take personalized packaging solution without CDN service)
axios
axios({
method: 'post'.url: '/user/12345'.data: {
firstName: 'Fred'.lastName: 'Flintstone'
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
Copy the code
The advantages and disadvantages:
- Create an XMLHttpRequest from the browser
- Make HTTP requests from Node.js
- Supporting Promise API
- Intercept requests and responses
- Transform request and response data
- Cancel the request
- Automatically convert JSON data
- The client supports CSRF/XSRF prevention
fetch
try {
let response = await fetch(url);
let data = response.json();
console.log(data);
} catch(e) {
console.log("Oops, error", e);
}
Copy the code
The advantages and disadvantages:
- Fetcht reports errors only for network requests, and considers 400 or 500 requests as successful requests, which need to be encapsulated and processed
- The FETCH does not carry cookies by default. Configuration items need to be added
- Fetch does not support abort and timeout control. The timeout control implemented by setTimeout and Promise.reject cannot prevent the request process from continuing to run in the background, resulting in a waste of quantity
- Fetch has no way of natively monitoring the progress of requests, whereas XHR does
Ajax reads and parses an instance of an XML document?
The answer:
var xhr = new XMLHttpRequest;//-> Is not compatible in IE7
xhr=new ActiveXObject("Microsoft.XMLHTTP");
xhr=new ActiveXObject("Msxml2.XMLHTTP");
xhr=new ActiveXObject("Msxml3.XMLHTTP");
Copy the code
//-> Lazy thinking
var getXHR = (function () {
//-> store the methods we need to get Ajax objects
var ajaxAry = [
function () {
return new XMLHttpRequest;
},
function () {
return new ActiveXObject("Microsoft.XMLHTTP");
},
function () {
return new ActiveXObject("Msxml2.XMLHTTP");
},
function () {
return new ActiveXObject("Msxml3.XMLHTTP"); }];//-> loop array, execute the four methods one by one
var xhr = null;
for (var i = 0; i < ajaxAry.length; i++) {
Function (){return new XMLHttpRequest; }(A1), execute without error, XHR is its return value and also our Ajax object, no catch, execute getXHR = A1, this overwrites the outside getXHR, encountered a break loop end
Function (){return new; //->IE6: function(){return new; //->IE6: function(){return new ActiveXObject("Microsoft.XMLHTTP"); }(A2), execute without error, then execute getXHR = A2, break to end the whole loop, then getXHR = A2
var tempFn = ajaxAry[i];
try {
xhr = tempFn();
} catch (e) {
continue;
}
getXHR = tempFn;
break;
}
if(! xhr) {throw new Error("Your browser version is too LOW, can you still have fun ~~");
}
returngetXHR; }) ();var xhr = getXHR();
xhr.open("get"."test.txt? _ =" + Math.random(), true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && /^2\d{2}$/.test(xhr.status)) {
var val = xhr.responseText;
console.log(val); }}; xhr.send(null);
Copy the code
Avoid returning data that is garbled
-> The front page is utF-8 encoding. If the data we request from the server is not IN UTF-8 encoding format, then the Chinese characters in the obtained content will be garbled
-> We need to use “UTF-8 to the end of the principle” : front-end pages, JS, CSS, backend code, database, request data transfer unified use a UTF-8 encoding
->[RESPONSE] Content-type :text/plain, application/json… Format the content in the response body
Front end: Sets the request header and gets the response header
Xhr.setrequestheader ([name],[value]);
Can use XHR. GetResponseHeader ([name])/XHR getAllResponseHeaders () to obtain the response headers;
Server side: Gets the request header and sets the response header
-> Response.writehead (200, {‘content-type’: ‘application/json’}); Set the response header information
-> In NODE we can use the request object to get the request information (start line, head, body)
Multiplexing versus multiplexing?
A: The work of delivering the data in the transport-layer message segment to the correct socket is called multiplexing.
After collecting data from different sockets on the source host, encapsulating header information to generate packet segments, the packet segments are transmitted to the network layer. This process is called multiplexing.
Connectionless multiplexing and demultiplexing refers to the process of allocating UDP sockets, which are identified by a binary containing a destination address and a destination port number. Therefore, if UDP packet segments with different source IP addresses and port numbers arrive at the host and have the same destination IP address and destination port number, the different packet segments are forwarded to the same UDP socket.
Connection-oriented multiplexing and demultiplexing refers to the allocation of TCP sockets, a TCP socket identified by a quad containing the source IP address, source port number, destination address, and destination port number. Therefore, when a TCP segment arrives on a host from the network, the host uses all four values to direct the segment to the corresponding socket.
UDP protocol?
A: UDP is a connectionless, unreliable transport layer protocol. It provides the bare minimum of functionality that the transport layer needs to implement, and adds little to IP other than reuse/decomposition capabilities and a small amount of error detection. UDP is applicable to application scenarios that require high real-time performance.
Features:
- UDP is called a connectionless transport layer protocol because the communication parties do not shake hands before sending packets. Because there is no handshake process, there is no latency for establishing a connection compared to TCP. Because there is no connection, there is no need to save the state of the connection in the end system.
- UDP provides best effort delivery service, that is, UDP protocol does not guarantee reliable delivery of data.
- UDP does not provide congestion control and traffic control mechanisms. Therefore, the rate of sending UDP packets is not limited.
- Because a UDP socket is identified only by destination address and destination port, UDP can support one-to-one, one-to-many, many-to-one, and many-to-many interactive communications.
- UDP header is small, only 8 bytes.
UDP packet segment structure
A UDP packet segment consists of the header and application data. The header of the packet segment contains four fields: the source port number, the destination port number, the length, and the check and. The length of each field is two bytes. The length field indicates the length of the entire packet segment, including the header and the size of the application data. Checksum is an error-checking mechanism provided by UDP. Although the error verification mechanism is provided, UDP is helpless for error recovery.
TCP protocol?
A: TCP is a connection-oriented transport layer protocol that provides reliable data transmission services.
Features:
- TCP is connection-oriented. Before the two parties communicate, they need to establish a connection through a three-way handshake. It needs to maintain the state information of the connection between the two parties in the end system.
- TCP provides reliable data transmission services through mechanisms such as serial number, confirmation number, scheduled retransmission, and verification.
- TCP provides point-to-point services, that is, it is a connection between a single sender and a single receiver.
- TCP provides full-duplex service, that is, the two parties can send and receive data to each other.
- TCP provides the congestion control mechanism. When the network is congested, TCP controls the rate of sending data, reducing packet loss and reducing the degree of congestion on the network.
- TCP provides a traffic control mechanism to ensure that the sending and receiving rates are the same. If the cache received by the receiver is very small, the sender slows down the sending rate to avoid packet loss due to cache filling.
TCP packet segment structure
A TCP packet segment consists of a header and data. The header is usually 20 bytes.
Source port and destination port numbers are used for multiplexing and decomposing packet segments.
32 – bit serial number and 32 – bit confirmation number for reliable data transport services.
Flow control is implemented with a 16-bit receive window field that represents the number of bytes the receiver is willing to receive.
A 4-bit header length field that indicates the length of the TCP header in 32-bit words.
A 6-bit flag field, the ACK field for indicating that the value of the confirmation sequence number is valid, and the RST, SYN, and FIN bits for connection establishment and disconnection. The PSH segment is set to indicate that the receiver should immediately hand over the data to the upper layer, and the URG field is used to indicate that urgent data exists in the packet segment.
Checksums provide error detection of data.
TCP three-way handshake process
For the first handshake, the client sends a SYN request packet to the server. The SYN flag in the header of the packet is 1, and the serial number field is an optional random number. It represents the initial sequence number of the client data.
On the second handshake, after receiving the SYN request packet from the client, the server allocates TCP cache and variables for the connection and then sends the SYN ACK packet to the client. The SYN and ACK bits in the header of the PACKET are set to 1. This is an acknowledgement of a SYN connection request, and the sequence number field is an optional random number generated by the server that represents the initial sequence number of the server data. The confirmation number field is the serial number sent by the client plus one.
For the third handshake, after the client receives a positive response from the server, it also allocates cache and variables for the TCP connection and sends an acknowledgement to the server. The third handshake can carry data in a message segment.
In my opinion, the TCP three-way handshake is the process of confirming the initial sequence number, telling each other what sequence number segment can be correctly received. The third handshake is used by the client to confirm the initial sequence number of the server. If only two handshakes are used, there is no way for the server to know if its serial number has been confirmed. At the same time, this is to prevent invalid request packet segments from being received by the server and causing errors.
TCP wave four times
A TCP connection is full-duplex, that is, both parties can send and receive messages to each other. Therefore, disconnection requires confirmation from both parties.
After the first wave, the client determines that no data needs to be sent to the server, and sends a FIN packet to the server to disconnect the client from the server. The client enters the FIN_WAIT_1 state.
For the second wave, after receiving the request to release the connection from the client, the server sends an acknowledgement packet to the client, indicating that it has received the request to release the connection from the client and will not receive data from the client in the future. However, because the connection is full-duplex, the server can also send data to the client at this point. The server enters the CLOSE_WAIT state. After receiving the acknowledgement, the client enters the FIN_WAIT_2 state.
After the third wave, the server sends all data and sends a FIN packet to the client to disconnect the connection from the server to the client. The device enters the LAS T_ACK state.
For the fourth wave, the client sends an acknowledgement to the server after receiving the FIN request and enters the TIME_WAIT phase. This phase lasts for a period of time, which is the maximum lifetime of the packet segment on the network. If the server does not resend the request within this period, the client enters the CLOSED state. Resend the acknowledgment segment if a resend request is received from the server. The server enters the CLOSED state after receiving the acknowledgement packet segment from the client, and the full-duplex connection is released.
The reason why TCP uses the quadruple wave is that TCP connections are full-duplex. Therefore, the two parties need to release the connection to the other party respectively. If the connection is released, only the representative table can no longer send data to the other party.
During the last wave, the client waits for a period of time to shut down the server. This prevents the server from being shut down properly due to the loss or error of the acknowledgement packet sent to the server.
State transition diagram
ARQ protocol
ARQ protocol refers to the automatic retransmission request, which ensures reliable data delivery through timeout and retransmission. It is a very important mechanism of TCP protocol to achieve reliable data transmission.
It is divided into stop wait ARQ protocol and continuous ARQ protocol.
1. Stop waiting for ARQ
The basic principle of the stop-wait ARQ protocol is that for each packet sent by the sender, a timer is set for that packet. When the confirmation of the sending packet is returned, the timer is cleared and the next packet is sent. If no positive response from the sent group is received within the specified time, the previous group is resend.
For the receiving side, each time it receives a packet, it returns an affirmative response to the packet, and when it receives a redundant packet, it directly discards it and returns an acknowledgement of the redundant packet. When receiving packet damage, discard it directly.
The disadvantage of using the stop-wait ARQ protocol is that each packet must wait until the packet is confirmed before the next packet can be sent, which will cause low channel utilization.
Ii. Continuous ARQ protocol
Continuous ARQ protocol is used to solve the problem that the utilization rate of stop-wait ARQ protocol for channel is too low. It sends a group of packets continuously, and then waits for the confirmation of the reply to the packet. For how to deal with the possible error recovery situation in the packet, generally can use the sliding window protocol and select retransmission protocol to achieve.
- Sliding window protocol
Using the sliding window protocol, maintain a send window in the sender, send window before group is the group has been sent and confirmed, send window contains the hair has been sent but not yet confirmed the grouping and allowed to send but haven’t send packet, send window after grouping is also not allowed to send packet in the cache. When the sender sends a group to the receiver, all the groups in the window are sent in sequence and a timer is set. This timer can be interpreted as the earliest group that has not received confirmation. If you receive a confirmation reply from a group within the time of the timer, slide the window and move the head of the window to a position after the confirmation group. At this time, if there are still sent but no confirmation groups, reset the timer, if there is no timer off. If the timer times out, resend all subgroups that have been sent but have not received confirmation.
The receiver uses a cumulative acknowledgement mechanism, in which the receiver returns a group’s affirmative response for all groups that arrive in sequence. If an out-of-order packet is received, the receiver simply discards it and returns a yes for the most recent packet that arrived in order. Using cumulative acknowledgements ensures that the groups before the confirmation number have arrived in sequence, so the send window can be moved to the end of the confirmed groups.
The disadvantage of the sliding window protocol is that it uses the cumulative confirmation mechanism. If only the first group in the window is lost, and the subsequent groups arrive in sequence, then the sliding window protocol will resend all the groups, resulting in a large number of unnecessary groups discarded and retransmitted.
- Select the retransmission protocol
Because sliding Windows use cumulative validation, there are a lot of unnecessary grouped retransmissions. Using the selective retransmission protocol can solve this problem.
The select retransmission protocol maintains a send window at the sender. Before the sending window is the sent and confirmed groups, the window contains the sent but not confirmed groups, confirmed groups out of order, and allowed to send but not yet sent groups, after the sending window is the cache is not allowed to send groups. The biggest difference between the selected retransmission protocol and the sliding window protocol is that the sender creates a timer for each packet when sending it. When the sender receives an acknowledgement from a group, it cancels the timer of the group and determines whether there are continuous acknowledgement groups headed by the window header after receiving the group. If so, it moves the window backward. If not, it identifies the group as the received out-of-order group. When a packet timer expires, the packet is retransmitted.
On the receiving side, it will confirm every correctly received group, no matter whether the group is in order or out of order. The out-of-order group will be cached until all the out-of-order groups have reached an ordered sequence, and then it will be delivered to the upper layer. If a packet cannot be received correctly, the receiver ignores the packet directly.
TCP’s reliable transport mechanism
TCP’s reliable transport mechanism is based on continuous ARQ protocol and sliding window protocol.
TCP protocol in the sender to maintain a send window, send window before the message is already sent and confirmed the message, send window contains a message has been sent but not yet confirmed and allowed to send but haven’t send a message, send window message later period of the cache is not allowed to send a message. When the sender sends a packet to the receiver, it sends all the packet segments in the window in sequence and sets a timer. The timer can be regarded as the earliest packet segment that is not acknowledged. If a reply is received from a certain packet segment within the timer period, the system slides the window backward to the next position of the packet segment. If there are still sent packets but no acknowledgement, the system resets the timer. If there are no packets, the system shuts down the timer. If the timer times out, the system resends all the sent but unacknowledged packets and sets the timeout interval to twice as long as before. When the sender receives the three redundant acknowledgement replies from the receiver, it indicates that the subsequent packet segments are likely to be lost. In this case, the sender enables the fast retransmission mechanism. That is, the sender sends all the acknowledged packets before the current timer ends.
The receiver uses the cumulative acknowledgement mechanism. For all the segments that arrive in sequence, the receiver returns a positive reply for each segment. If an out-of-order segment is received, the receiver discards the segment and returns an affirmative response to the most recent sequential segment. The use of cumulative acknowledgment ensures that the segments before the returned acknowledgment number have arrived in sequence, so the send window can be moved to the end of the acknowledged segment.
The size of the sending window varies, and is determined by the remaining size of the receiving window and the degree of congestion on the network. TCP controls the sending rate of packets by controlling the length of the sending window.
However, TCP is not exactly the same as the sliding window protocol because many TCP implementations cache out-of-order segments and retransmit only one segment when retransmission occurs. Therefore, the reliable transmission mechanism of TCP is more like a hybrid of the sliding window protocol and the selective retransmission protocol.
TCP traffic control mechanism
TCP provides the traffic control service. The purpose of this service is to control the sending rate of the sender and ensure that the receiver can receive the packets in time. If the sending rate is higher than the receiving rate, the packet segment will be lost. The receiver mainly tells the sender the size it can receive through the receiving window, and the sender adjusts the size of the sending window according to the size of the receiving window to control the sending rate.
TCP congestion control mechanism
TCP congestion control is mainly based on network congestion is to control the sender of the data transmission speed, if the network is in a state of congestion, the sender will send the rate of decrease, so that increase on the one hand, in order to avoid the network congestion degree, on the other hand is also in order to avoid network congestion can be caused by packet loss.
TCP congestion control uses four mechanisms: slow start, congestion avoidance, fast retransmission, and fast recovery.
Is the basic idea of slow start, because at the time of sending fang began sending data, do not know in the network congestion degree, so at a relatively low rate of the first to send, to carry on the test, each received a confirmation message, will launch window length plus one, so that after each time RTT, send window length will be doubled. When the size of the sending window reaches a threshold, the congestion avoidance algorithm is entered.
To avoid possible congestion, the congestion avoidance algorithm doubles the size of the sending window from one RTT to one RTT, and only increases the length by one. This changes the window growth rate from exponential growth to additive linear growth.
Fast retransmission means that when the sender receives three redundant acknowledgement packets, TCP uses the cumulative acknowledgement mechanism, so packet segments may be lost. Therefore, the instant retransmission mechanism is used to send all the packets that have been sent but have not received any acknowledgement before the timer ends.
Fast recovery is the follow-up to fast retransmission. Because congestion may have occurred in the network, the threshold value of slow start is reduced to half of the original value, and then the value of the congestion window is set to the threshold value after half, and then the congestion avoidance algorithm is implemented to make the congestion window slowly increase additive. The simple way to think about it is, multiplicative minus, additive plus.
TCP considers that network congestion is mainly determined by the number of retransmission times of packet segments. It adjusts the slow start threshold according to the degree of congestion on the network and uses the above four mechanisms alternately to achieve congestion control.
What’s the difference between Post and Get?
A: Post and Get are two methods of HTTP requests.
-
(1) From the perspective of application scenarios, GET request is an idempotent request. Generally, GET request is used for scenarios that have no impact on server resources, such as requesting a web page. Post, on the other hand, is not an idempotent request and is generally used in situations that affect server resources. Things like registering users.
-
(2) Because of different application scenarios, browsers generally cache Get requests, but rarely CACHE Post requests.
-
(3) In terms of the format of the sent message, the entity part of the Get request message is empty, while the entity part of the Post request message is generally the data sent to the server.
-
(4) But the Get request can also put the parameters of the request into the URL to send to the server,
- One aspect of this approach is that it is less secure than a Post request because the requested URL is retained in the history. And browsers have a length limit on urls, which affects the length of data sent in GET requests. This restriction is browser-specific, not RFC specific. Also, the argument passing of POST supports more data types.
Why does DNS use UDP as the transport layer protocol?
A: DNS uses UDP as the transport layer protocol to avoid the connection delay caused by TCP.
Because in order to get a domain name IP address query tend to multiple domain name server, if using the TCP protocol, so every request connection time delay, so that made the DNS service is slow, because most address query request, is the browser of the requested page, this will cause web waiting for a long time.
The UDP DNS protocol has a problem. Due to historical reasons, the minimum MTU of the physical link is 576. Therefore, to limit the packet length to 576, the LENGTH of UDP packet segment is limited to 512 bytes. Beyond 512 bytes, the UDP-based DNS protocol is truncated to 512 bytes, and the user may get an incomplete DNS response. Once the length of DNS packets exceeds the limit, they are not divided into multiple packet segments like TCP. UDP does not maintain connection status, so we cannot determine which packet segments belong to the same data. UDP intercepts redundant data.
To solve this problem, we can use THE TCP protocol to request packets.
Another problem with DNS is security. There is no way to be sure that the reply we are getting is a secure reply, because the reply can be forged by someone else. So now DNS over HTTPS solves this problem.
What about CDN services?
A: CDN is a content distribution network, which provides users with the nearest access function through the cache of source website resources and the use of multiple servers located in different regions and different operators. In other words, the user’s request is not directly sent to the source website, but to the CDN server, and the CND server will locate the request to the nearest server containing the resource to request. This helps speed up the web site and, in this way, reduces the load on the source server.
What are forward and reverse proxies?
Answer: The proxy that we often say is also refers to the forward proxy, forward proxy process, it hides the real request client, the server does not know who the real client is, the service that the client requests is replaced by proxy server to request.
Reverse proxy to hide the real server, when we request a web site, there may be hundreds of thousands of servers behind the service for us, but which is a specific, we don’t know, also don’t need to know, we just need to know who is the reverse proxy server, the reverse proxy server will help us put forward requests to the real server. Reverse proxies are commonly used for load balancing.
Two ways to achieve load balancing?
A: One way is to use a reverse proxy. Users’ requests are sent to the reverse proxy service, and then the reverse proxy server forwards the requests to the real server, so as to realize the load balancing of the cluster.
The other is DNS, which can be used for load balancing on redundant servers. Because today’s large web sites typically use multiple servers, a single domain name can have multiple server addresses. When a user requests a web site domain name, the DNS server returns a set of server IP addresses corresponding to the domain name, but in each response, the order of these IP addresses is cycled, and the user generally chooses the first address to send the request. In this way, users’ requests are evenly distributed to different servers to achieve load balancing. A disadvantage of this approach is that the DNS server has cache. Therefore, if a server fails, the same IP address may still be returned after domain name resolution, causing access problems.
Instant messaging implementation, short polling, long polling, SSE and WebSocket differences?
A: The purpose of both short and long polling is to enable instant communication between the client and the server.
The basic idea of short polling is that the browser sends HTTP requests to the browser at regular intervals, and the server responds directly to the request, regardless of whether there is any data update. This way to achieve instant communication, in essence, or the browser to send a request, the server to accept the request of a process, by allowing the client to continue to request, so that the client can simulate the real-time received server data changes. This approach has the advantage of being relatively simple and easy to understand. The disadvantage of this approach is that it wastes resources on both the server and client side because of the constant establishment of HT TP connections. As the number of users increases, the pressure on the server side increases, which is quite unreasonable.
The basic idea of long polling is that the client sends a request to the server first. When the server receives a request from the client, the server does not respond directly. Instead, the server suspends the request and checks whether the data on the server is updated. If there is an update, it responds, and if there is no data, it does not return until a certain time limit is reached. After processing the information returned from the server, the client-side JavaScript response handler makes another request to re-establish the connection. The advantage of long polling over short polling is that it significantly reduces the number of unnecessary HTTP requests and saves resources in comparison. The disadvantage of long polling is that hanging connections can also lead to wasted resources.
The basic idea of SSE is that the server uses streaming information to push information to the server. Strictly speaking, the HTTP protocol does not allow the server to actively push information. A workaround, however, is for the server to declare to the client that the next message to be sent is a stream. That is, instead of sending a one-time packet, a stream of data is sent continuously. Instead of closing the connection, the client waits for a new data stream from the server, as in the case of video playback. SSE uses this system to push information to the browser using streaming information. It is based on THE HTTP protocol and is currently supported by all browsers except IE/Edge. Compared with the previous two methods, it does not need to establish too many HTTP requests, and saves resources in comparison.
All three are HTTP based in nature and can be implemented using the WebSocket protocol. WebSocket is a new protocol defined by Html5. Different from the traditional HTTP protocol, this protocol allows the server to actively push information to the client. The disadvantage of using the WebSocket protocol is the complexity of configuration on the server side. WebSocket is a full-duplex protocol, that is, the communication parties are equal and can send messages to each other, while SSE is one-way communication, and only the server can push information to the client. If the client needs to send information, it belongs to the next HTTP request.
Implement a site where page actions do not refresh the entire page and respond correctly when the browser moves forward and backward. Give your technical implementation plan?
A: AJAX can be said to greatly improve the user’s browsing experience compared to hopping from page to page, and it’s nice not to see a blank screen between pages. But many older AJAX applications did not allow the browser to move forward and backward, which meant that users could refresh their site and immediately return to the original location, and there was no way to switch history using the browser’s forward and backward buttons.
For the first problem, it is relatively easy to solve, just use cookies or localStorage to record the state of the application, read the state when refreshing the page, and then send the corresponding Ajax request to change the page. But the second problem is more troubling, and first comes the modern browser solution.
JQuery interview questions
Jquery features, talk about jquery?
A:
- JQuery is a lightweight JS framework, jQuery core JS file is only tens of KB, does not affect the speed of page loading. It’s much lighter than Extjs.
- JQuery’s selectors are easy to use. For example, if I want to find the adjacent element js of a DOM object, IT may take several lines of code, whereas jQuery can do it in one line, or if I want to change the color of a table in one line, jQuery can do it in one line.
- JQuery’s chain operations allow you to write multiple operations in one line of code.
- JQuery also makes it easier for JS to manipulate CSS code, and the code is much more readable than JS.
- JQuery simplifies AJAX operations by allowing the backend to communicate with the foreground only by returning a JSON-formatted string.
- JQuery is basically compatible with today’s major browsers, so you don’t have to worry about browser compatibility.
- JQuery has rich third-party plug-ins, such as tree menu, date control, image switch plug-in, pop-up window and other basic front page components have corresponding plug-ins, and use jQuery plug-in to make the effect is very dazzling, and you can adapt and package plug-ins according to their own needs, simple and practical.
- JQuery provides an extension interface: jquery.extend (object). You can add new functions to the jQuery namespace. All jQuery plug-ins are developed based on this extension interface.
How do jquery objects and DOM objects convert?
A:
[0]
Can be converted to a DOM object$(domObject)
Can be converted to jQuery objects
How to convert an array to a JSON string in jquery, and then back again?
A:
$.fn.stringifyArray = function(array) {
return JSON.stringify(array)
}
$.fn.parseArray = function(array) {
return JSON.parse(array)
}
Copy the code
Then call:
$("").stringifyArray(array)
Copy the code
Have you seen the jQuery source code? Can you give a brief overview of how it works?
A:
1. Closure mechanism;
// The following is an excerpt from jquery source code
(function( window.undefined ) {
/* Source code */}) (window );
Copy the code
The above snippet of code comes from the 1.9.0 jquery source code, it is a pollution-free JS plug-in standard writing method, the technical term is called closure. You can think of it simply as a function that, unlike normal functions, has no name and executes immediately
We have changed the variables into local variables, which can not only improve the running speed, but more importantly, when we reference jquery JS files, there will not be too many variables in jquery and other JS framework variable naming conflicts. Variable declarations in closures do not contaminate external global variables; ;
2. As an attribute of the global.
window.jQuery = window.$ = jQuery;
Copy the code
This sentence exports the jQuery objects we defined in the closure as global variables jQuery and $, so we can use jQuery and $directly externally.
The window is the default JS context, so binding an object to the window becomes a traditional global variable.
3, the core function, is the selector;
It is easy to find the declaration of jquery object. If you look at it, you will find that our jquery object is init object.
jQuery = function( selector, context ) {
return new jQuery.fn.init( selector, context, rootjQuery );
}
Copy the code
Jquery.fn is the prototype of a jQuery object. Fn is the prototype of a jQuery object.
jQuery.fn = jQuery.prototype;
jQuery.fn.init.prototype = jQuery.fn;
Copy the code
Init (fn) {fn: fn; fn: fn; fn: fn; fn: fn; That is, the init object has the same prototype as jQuery, so the init object we return above has the same properties and methods as the jQuery object.
We’re not going to go into the logic and implementation of init, but it’s important to know that jQuery wraps a DOM object around it, and finding one or more DOM objects is left to the Sizzle selector,
JQuery objects have many properties and methods; In terms of properties, there is only one property we need to focus on, and that is the [0] property, which is essentially a native DOM object.
Most of the time, we need the [0] attribute to switch between jQuery and DOM objects.
As you can see from the screenshot, the jQuery object is basically a native DOM object in [0] position and a series of easy methods.
The attribute of index 0 can be seen briefly in a small piece of code, which is the source of the DOMElement selector in the init method.
// Handle $(DOMElement)
if ( selector.nodeType ) {
/* You can see that the DOM object is assigned to the [0] position of the jQuery object */
this.context = this[0] = selector;
this.length = 1;
return this;
}
Copy the code
This snippet of code, which can be found in the jquery source code, handles the case where the selection argument passed in is a DOM object.
As you can see, the DOM object is obviously assigned the position of the jQuery object index 0 and the context property
. The code not only shows this, but also shows how easy it is to convert a DOM object into a jQuery object using $(DOMElement).
4. Ready method
$(function(){}) or ready;
The ready method of jquery can be easily implemented by maintaining an array of functions and checking whether the DOM has been loaded. If so, all the functions in the array will be triggered.
With this in mind, LZ has come up with a small example that he wrote a long time ago.
(function( window.undefined ) {
var jQuery = {
isReady:false.// Indicates whether the document load is complete
readyList: [].// Sequence of functions
// Implement the onload event
ready : function(fn){
// If it is a function, add it to the function sequence
if(fn && typeof fn == 'function' ){
jQuery.readyList.push(fn);
}
// When the file is loaded, execute the function sequence.
if(jQuery.isReady){
for(var i = 0; i < jQuery.readyList.length ; i++){ fn = jQuery.readyList[i]; jQuery.callback(fn); }returnjQuery; }},/ / callback
callback : function(fn){
fn.call(document,jQuery); }};// Export objects
window$=window.jQuery = jQuery;
// Check whether the load is complete
var top = false;
try {
top = window.frameElement == null && document.documentElement;
} catch(e) {}
if ( top && top.doScroll ) {
(function doScrollCheck() {
try {
top.doScroll("left");
jQuery.isReady = true;
jQuery.ready();
} catch(e) {
setTimeout( doScrollCheck, 50 );
}
})();
}
}(window));
Copy the code
This code is extracted from the previous example by LZ. The implementation logic is very simple, but it can achieve the effect of jQuery’s ready method.
Extend method
A brief description of the two commonly used extend methods.
- Extend (jquery.fn. extend); extend (jquery.extend); extend (jquery.extend); extend (jquery.extend);
- 2. The extend methods extend object properties to the first object if they have two arguments of type object. When extending, a Boolean argument can be added to control deep copy.
Jquery find,children,filter
A:
- A filter is an operation on an element of its own collection,
- Children is a retrieval of child elements,
- Find is a retrieval operation on its descendant elements
The.children(selector) method returns all the children(only the children) of each element in the matching set of elements. Parameter Indicates that elements are filtered by the selector. This parameter is optional.
The.find(selector) method returns the descendants of each element in the matched set of elements. The parameter is mandatory and can be used to filter elements for selectors and jquery objects.
The.find() method is similar to the.children() method, except that the latter only traverses a single level down the DOM tree. The children here, I understand as sons, are only traversed at the son level.
How are jQuery queues implemented? Where can queues be used?
A: Queue(), dequeue(), clearQueue(), etc. After animate (), all functions are executed in sequence. After animate (), all functions are executed in sequence. Ajax and other events to be executed in chronological order.
Let’s explain what each of these methods means.
Queue (name,[callback]): When only one argument is passed, it returns and points to the queue of the first matched element (it will be an array of functions, the queue name is fx by default); When two arguments are passed in, the first argument is the queue name that defaults to FX, and the second argument is a function that adds a function to the end of the queue of matched elements. When the second argument is a function array, it replaces the queue of matching elements with a new queue. Maybe this is a little confusing.
Dequeue (name): This is easy to understand, which is to remove a queue function from the front of the queue and execute it.
ClearQueue ([queueName]): This method is new in 1.4. Clears all queues that have not yet executed on an object. The default is fx. But I don’t think this method is very useful. The clearQueue method is implemented by passing the second argument of two arguments to queue().
Now, we want to achieve the effect that we have a number square labeled 1 through 7, and we want the seven squares to fall from left to right; Write a later
; What if, at this point, you want to switch the execution order of something, say, you want to drop 5 and then start falling 3, or add 8 to 15 new 8 beepers?
Rewrite? Be careful what you do in there? Obviously, we need another simple and convenient way to achieve this effect, which is the jQuery queue control method. ;
So that makes it a little bit simpler. How to do that?
- Create a new array and place the animation functions in it. ;
- Queue this array of animated functions to the slideList queue;
- Fetch the first function in the slideList queue with dequeue and execute it;
- The first function is executed initially.
Without further discussion of the clearQueue() method, which is called by the stop button in the demo, you can also use the queue() method to replace the current queue with an empty array (I recommend empty array substitution). , more intuitive).
What is the difference between jQuery and jQuery UI?
A:
-
JQuery is a JS library that provides functions such as selectors, property modification and event binding.
-
JQuery UI is a plug-in designed on the basis of jQuery and using the extensibility of jQuery.
- Provides some common interface elements, such as dialog boxes, drag behavior, resizing behavior, and so on
What’s the difference between jQuery and Zepto? What are their usage scenarios?
A: Zepto is primarily for mobile devices and only supports newer browsers, which benefits from less code and better performance.
Jquery is mainly compatible, can run on a variety of PC, mobile, the advantage is compatible with a variety of browsers, the disadvantage is a large amount of code, while considering compatibility, performance is not good enough.
Jq itself has noticed this always, all of its 2.x versions do not support IE6, 7, and 8
How to optimize jQuery performance?
A:
-
The performance of class-based selectivity is expensive compared to Id selectors because you need to traverse all DOM elements.
-
DOM, which is frequently manipulated, is cached before manipulation. It is better to use jQuery’s chain call.
- Such as:
var str=$("a").attr("href");
- Such as:
-
The for loop
for (var i = size; i < arr.length; i++) { } Copy the code
Each time the for loop looks for the length property of the array (arR), setting a variable at the beginning of the loop to store this number can make the loop run faster:
for (var i = size, length = arr.length; i < length; i++) {
}
Copy the code
How is it possible to bind multiple events to a jQuery object at the same time?
A:
$ele.on('eventName', handle1);
$ele.on('eventName', handle2);
$ele.on('eventName', handle3);
Copy the code
The eventName of the $ele element has an array that listens for a handle and puts a handle in it at a time
That is, the stack, and then execute it once when the event is triggered
The monitor up there is equivalent to
$ele.eventHandle['eventName'] = [];
$ele.eventHandle['eventName'].push(handle1);
$ele.eventHandle['eventName'].push(handle2);
$ele.eventHandle['eventName'].push(handle3);
Copy the code
When $ele.trigger(‘eventName’) is triggered, the handler is removed from the stack and executed
while($ele.eventHandle['eventName'].length) {
handle = $ele.eventHandle['eventName'].pop();
handle();
}
Copy the code
The last execution monitored first;
Vue. Js interview questions
Vue. Js route hook function?
A: The home page can control navigation jump, beforeEach, afterEach, etc., generally used for page title modification. Some require login to adjust the page’s redirection function.
- BeforeEach has 3 main parameters to, from, and next.
- To: route Indicates the destination route object to be entered.
- From: route Indicates the route that the current navigation is about to leave.
- Next: function must call the method resolve hook. The execution depends on the call parameters of the next method. You can control the jump of web pages
What is vuex? How to use it? Which functional scenarios use it?
A:
- Reading-only states are concentrated in stores; The way to change that is to submit mutations, which is a simultaneous thing; Asynchronous logic should be encapsulated in actions.
- Import store and inject in main.js. Create a new directory store… export
- The scenarios include: status between components, music playing, login status, and adding to shopping cart in a one-page application
- State: Vuex uses a single state tree, that is, each application will contain only one store instance, but a single state
- Trees and modularity are not in conflict. The state of the stored data cannot be modified directly.
- Mutations: The method defined by Mutations dynamically modifies the state or data in Vuex’s store
- Getters: A vUe-like computational property that filters data.
- Action: Actions can be understood as the method of treating the data in mutations into a method that can process the data asynchronously, simply speaking, it is to manipulate the data asynchronously. The View layer distributes actions through store.dispath
- Modules: When the project is particularly complex, we can make each module have its own state, mutation, action and getters, which makes the structure very clear and easy to manage
How does vue.js make CSS work only in the current component?
A: Modify the current component
What does the vue.js directive V-EL do?
A: Provide a DOM element that already exists on the page as the mount target for the Vue instance. It could be a CSS selector, or it could be an HTMLElement instance,
How to use plug-ins in vue.js?
A:
- Using ES6 import… The from… The syntax or CommonJS require() method introduces plug-ins
- Use (MyPlugin, {someOption: true}) use(MyPlugin, {someOption: true})
Does vue.js route jump between routes?
A: Declarative (label jump)
<router-link :to="index">
Copy the code
Programming (JS jump)
router.push('index')
Copy the code
When can data in vue.js components use objects?
A: When components are reused, all component instances share data. If data is an object, the modification of data by one component will affect all other components. Therefore, data needs to be written as a function, which will be called once every time it is used to obtain new data. When we use new Vue(), we can set data as an object or as a function. Because new Vue() generates a root component that is not reused, there is no sharing of data
What are the navigational guards in vue-router?
A: Complete navigation parsing process
- Navigation is triggered.
- Call the leave guard in the inactivated component.
- Call global
beforeEach
The guards. - Called in a reused component
beforeRouteUpdate
Guard (+ 2.2). - Called in the routing configuration
beforeEnter
. - Parse the asynchronous routing component.
- Called in the active component
beforeRouteEnter
. - Call global
beforeResolve
Guard (+ 2.5). - Navigation confirmed.
- Call global
afterEach
Hook. - Trigger a DOM update.
- Call with the created instance
beforeRouteEnter
Guard passnext
The callback function of.
In which lifecycle do vue.js Ajax requests go?
A:
- At created, in the view
dom
It’s not rendered, so if you just go fuck itdom
Node, the associated element could not be found - In Mounted, because at this time
dom
It’s already rendered, so you can do it directlydom
node
In most cases, it is placed in Mounted to ensure logical uniformity. Because the lifecycle is executed synchronously, ajax is executed asynchronously
How to separate the same logic in vue.js?
A: Vue. mixins are used to mix some common logic into components for each lifecycle, function, etc
Vue.mixin = function (mixin: Object) {
this.options = mergeOptions(this.options, mixin); // Merge the currently defined properties into each component
return this
}
export function mergeOptions (
parent: Object,
child: Object, vm? : Component) :Object {
if(! child._base) {if (child.extends) { // recursively merges extends
parent = mergeOptions(parent, child.extends, vm)
}
if (child.mixins) { // Merge mixins recursively
for (let i = 0, l = child.mixins.length; i < l; i++) {
parent = mergeOptions(parent, child.mixins[i], vm)
}
}
}
const options = {} // Merge attributes and life cycles
let key
for (key in parent) {
mergeField(key)
}
for (key in child) {
if(! hasOwn(parent, key)) { mergeField(key) } }function mergeField (key) {
const strat = strats[key] || defaultStrat
// Call different attribute merge policies to merge
options[key] = strat(parent[key], child[key], vm, key)
}
return options
}
Copy the code
Common performance optimizations in Vue.js?
Answer: 1. Coding optimization:
- 1. Do not put all data in data. Getter and setter will be added to data, and the corresponding watcher will be collected
- 2.
vue
Binding events to each element in V-for requires an event broker - 3.
SPA
The page uses the keep-alive cache component - 4. Split components (increase reusability, increase code maintainability, reduce unnecessary rendering)
- 5.
v-if
When the value is false, the internal instruction will not execute and has the blocking function. In many cases, v-if is used instead of V-show - 6.
key
Guaranteed uniqueness (defaultvue
In-place reuse strategy will be adopted.) - 7.
Object.freeze
Frozen data - 8. Rational use of lazy and asynchronous components
- 9. Try to use the Runtime version
- 10. Data persistence issues (stabilization, throttling)
2.Vue
Loading performance optimization:
- Import third-party modules on demand (
babel-plugin-component
) - Scroll to visual area for dynamic loading (Tangbc.github. IO /vue-virtual…)
- Lazy loading of images (github.com/hilongjw/vu…)
3. User Experience:
app-skeleton
Skeleton screenapp-shell
App shellpwa
4.SEO
Optimization:
- Prerender plugin
prerender-spa-plugin
- Server side rendering
ssr
5. Packaging optimization:
- use
cdn
To load a third-party module - Multithreaded packaging
happypack
splitChunks
Extract public filessourceMap
generate
6. Cache, compression
- Client cache, server cache
- The service side
gzip
The compression
Talk about your understanding of the MVVM principle of vue.js?
A: Traditional MVC
Traditional MVC is all about
- M is for business Model, Model
- V for user interface, View
- C is the Controller, Controller.
The purpose of using MVC is to separate the M and V implementation code so that the same program can use different representations.
User operations request server routing, which invokes the corresponding controller for processing, and the controller retrieves data. The result is returned to the front end and the page is re-rendered
MVVM
MVVM stands for model-view-ViewModel
- The Model represents the data Model, where you can also define the business logic for data modification and manipulation.
- View represents the UI component that transforms the data model into a UI for presentation.
- A ViewModel listens for changes in Model data, controls the behavior of the View, and handles user interactions
Traditional front ends render data manually to the page. MVVM mode does not require users to manually manipulate DOM elements.
Binding data to the viewModel layer automatically renders the data to the page and notifies the viewModel layer to update the data when the view changes.
The ViewModel is the bridge in our MVVM pattern.
In MVVM architecture, there is no direct connection between View and Model, but interaction through ViewModel. The interaction between Model and ViewModel is bidirectional, because the change of View data will be synchronized to Model. Changes to Model data are immediately reflected in the View.
ViewModel connects View layer and Model layer through two-way data binding, and the synchronization between View and Model is completely automatic, without human intervention, so the developer only needs to pay attention to the business logic, do not need to manually manipulate DOM, do not need to pay attention to the same step problem of data state, Complex data state maintenance is managed entirely by MVVM.
Can you explain the principle of vue.js responsive data?
A:
- 1. Core point:
Object.defineProperty
- 2. The default
Vue
When the data is initialized, it givesdata
Attribute use inObject.defineProperty
Redefine all attributes when the page retrieves the corresponding attribute. Dependency collection (collecting the watcher for the current component) notifying dependencies to update if properties change.
Object.defineProperty(obj, key, {
enumerable: true.configurable: true.get: function reactiveGetter () {
const value = getter ? getter.call(obj) : val
if (Dep.target) {
dep.depend() // ** collect dependencies ** /
if (childOb) {
childOb.dep.depend()
if (Array.isArray(value)) {
dependArray(value)
}
}
}
return value
},
set: function reactiveSetter (newVal) {
const value = getter ? getter.call(obj) : val
if(newVal === value || (newVal ! == newVal && value ! == value)) {return
}
if(process.env.NODE_ENV ! = ='production'&& customSetter) { customSetter() } val = newVal childOb = ! shallow && observe(newVal) dep.notify()/** Notifies dependencies to update **/}})Copy the code
How does template compilation work in vue.js?
A: Convert template to the render function
function baseCompile (template: string, options: CompilerOptions) {
const ast = parse(template.trim(), options) // 1. Convert the template to an AST syntax tree
if(options.optimize ! = =false) { // 2. Optimize the tree
optimize(ast, options)
}
const code = generate(ast, options) // 3. Spanning tree
return {
ast,
render: code.render,
staticRenderFns: code.staticRenderFns
}
})
Copy the code
const ncname = `[a-zA-Z_][\\-\\.0-9_a-zA-Z]*`;
const qnameCapture = ` ((? :${ncname}\ \ :)?${ncname}) `;
const startTagOpen = new RegExp(` ^ <${qnameCapture}`); // The re at the beginning of the tag captures the tag name
const endTag = new RegExp(` ^ < \ \ /${qnameCapture}[^ >] * > `); // Match at the end of the tag
const attribute = /^\s*([^\s"'<>\/=]+)(? :\s*(=)\s*(? :"([^"]*)"+|'([^']*)'+|([^\s"'=<>`]+)))? /; // Match the attribute
const startTagClose = /^\s*(\/?) >/; // Match tag end >
let root;
let currentParent;
let stack = []
function createASTElement(tagName,attrs){
return {
tag:tagName,
type:1.children:[],
attrs,
parent:null}}function start(tagName,attrs){
let element = createASTElement(tagName,attrs);
if(! root){ root = element; } currentParent = element; stack.push(element); }function chars(text){
currentParent.children.push({
type:3,
text
})
}
function end(tagName){
const element = stack[stack.length-1];
stack.length --;
currentParent = stack[stack.length-1];
if(currentParent){
element.parent = currentParent;
currentParent.children.push(element)
}
}
function parseHTML(html){
while(html){
let textEnd = html.indexOf('<');
if(textEnd == 0) {const startTagMatch = parseStartTag();
if(startTagMatch){
start(startTagMatch.tagName,startTagMatch.attrs);
continue;
}
const endTagMatch = html.match(endTag);
if(endTagMatch){
advance(endTagMatch[0].length);
end(endTagMatch[1])}}let text;
if(textEnd >=0 ){
text = html.substring(0,textEnd)
}
if(text){ advance(text.length); chars(text); }}function advance(n) {
html = html.substring(n);
}
function parseStartTag(){
const start = html.match(startTagOpen);
if(start){
const match = {
tagName:start[1].attrs:[]
}
advance(start[0].length);
let attr,end
while(! (end = html.match(startTagClose)) && (attr=html.match(attribute))){ advance(attr[0].length);
match.attrs.push({name:attr[1].value:attr[3]})}if(end){
advance(end[0].length);
return match
}
}
}
}
// Generate a syntax tree
parseHTML(`<div id="container"><p>hello<span>zf</span></p></div>`);
function gen(node){
if(node.type == 1) {return generate(node);
}else{
return `_v(The ${JSON.stringify(node.text)}) `}}function genChildren(el){
const children = el.children;
if(el.children){
return ` [${children.map(c=>gen(c)).join(', ')}] `
}else{
return false; }}function genProps(attrs){
let str = ' ';
for(let i = 0; i < attrs.length; i++){let attr = attrs[i];
str+= `${attr.name}:${attr.value}, `;
}
return `{attrs:{${str.slice(0, -1)}}} `
}
function generate(el){
let children = genChildren(el);
let code = `_c('${el.tag}'${
el.attrs.length? `,${genProps(el.attrs)}`:' '
}${
children? `,${children}`:' '
}) `;
return code;
}
// Generate new code from the syntax tree
let code = generate(root);
let render = `with(this){return ${code}} `;
// wrap as a function
let renderFn = new Function(render);
console.log(renderFn.toString());
Copy the code
Describe the principle of diff algorithm in vue. js.
A:
- 1. Compare peer nodes first and then child nodes
- 2. Determine if one parent has a son and the other doesn’t
- 3. They both have sons
- 4. Compare child nodes recursively
const oldCh = oldVnode.children // The old son
const ch = vnode.children // New son
if (isUndef(vnode.text)) {
if (isDef(oldCh) && isDef(ch)) {
// Compare children
if(oldCh ! == ch) updateChildren(elm, oldCh, ch, insertedVnodeQueue, removeOnly) }else if (isDef(ch)) { // The new son has no old son
if (isDef(oldVnode.text)) nodeOps.setTextContent(elm, ' ')
addVnodes(elm, null, ch, 0, ch.length - 1, insertedVnodeQueue)
} else if (isDef(oldCh)) { // If the old one has no new one, delete it
removeVnodes(oldCh, 0, oldCh.length - 1)}else if (isDef(oldVnode.text)) { // The old has text and the new has no text
nodeOps.setTextContent(elm, ' ') // Empty the old ones}}else if(oldVnode.text ! == vnode.text) {// The text is not the same replacement
nodeOps.setTextContent(elm, vnode.text)
}
Copy the code
function updateChildren (parentElm, oldCh, newCh, insertedVnodeQueue, removeOnly) {
let oldStartIdx = 0
let newStartIdx = 0
let oldEndIdx = oldCh.length - 1
let oldStartVnode = oldCh[0]
let oldEndVnode = oldCh[oldEndIdx]
let newEndIdx = newCh.length - 1
let newStartVnode = newCh[0]
let newEndVnode = newCh[newEndIdx]
let oldKeyToIdx, idxInOld, vnodeToMove, refElm
// removeOnly is a special flag used only by <transition-group>
// to ensure removed elements stay in correct relative positions
// during leaving transitions
constcanMove = ! removeOnlyif(process.env.NODE_ENV ! = ='production') {
checkDuplicateKeys(newCh)
}
while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) {
if (isUndef(oldStartVnode)) {
oldStartVnode = oldCh[++oldStartIdx] // Vnode has been moved left
} else if (isUndef(oldEndVnode)) {
oldEndVnode = oldCh[--oldEndIdx]
} else if (sameVnode(oldStartVnode, newStartVnode)) {
patchVnode(oldStartVnode, newStartVnode, insertedVnodeQueue, newCh, newStartIdx)
oldStartVnode = oldCh[++oldStartIdx]
newStartVnode = newCh[++newStartIdx]
} else if (sameVnode(oldEndVnode, newEndVnode)) {
patchVnode(oldEndVnode, newEndVnode, insertedVnodeQueue, newCh, newEndIdx)
oldEndVnode = oldCh[--oldEndIdx]
newEndVnode = newCh[--newEndIdx]
} else if (sameVnode(oldStartVnode, newEndVnode)) { // Vnode moved right
patchVnode(oldStartVnode, newEndVnode, insertedVnodeQueue, newCh, newEndIdx)
canMove && nodeOps.insertBefore(parentElm, oldStartVnode.elm, nodeOps.nextSibling(oldEndVnode.elm))
oldStartVnode = oldCh[++oldStartIdx]
newEndVnode = newCh[--newEndIdx]
} else if (sameVnode(oldEndVnode, newStartVnode)) { // Vnode moved left
patchVnode(oldEndVnode, newStartVnode, insertedVnodeQueue, newCh, newStartIdx)
canMove && nodeOps.insertBefore(parentElm, oldEndVnode.elm, oldStartVnode.elm)
oldEndVnode = oldCh[--oldEndIdx]
newStartVnode = newCh[++newStartIdx]
} else {
if (isUndef(oldKeyToIdx)) oldKeyToIdx = createKeyToOldIdx(oldCh, oldStartIdx, oldEndIdx)
idxInOld = isDef(newStartVnode.key)
? oldKeyToIdx[newStartVnode.key]
: findIdxInOld(newStartVnode, oldCh, oldStartIdx, oldEndIdx)
if (isUndef(idxInOld)) { // New element
createElm(newStartVnode, insertedVnodeQueue, parentElm, oldStartVnode.elm, false, newCh, newStartIdx)
} else {
vnodeToMove = oldCh[idxInOld]
if (sameVnode(vnodeToMove, newStartVnode)) {
patchVnode(vnodeToMove, newStartVnode, insertedVnodeQueue, newCh, newStartIdx)
oldCh[idxInOld] = undefined
canMove && nodeOps.insertBefore(parentElm, vnodeToMove.elm, oldStartVnode.elm)
} else {
// same key but different element. treat as new element
createElm(newStartVnode, insertedVnodeQueue, parentElm, oldStartVnode.elm, false, newCh, newStartIdx)
}
}
newStartVnode = newCh[++newStartIdx]
}
}
if (oldStartIdx > oldEndIdx) {
refElm = isUndef(newCh[newEndIdx + 1])?null : newCh[newEndIdx + 1].elm
addVnodes(parentElm, refElm, newCh, newStartIdx, newEndIdx, insertedVnodeQueue)
} else if (newStartIdx > newEndIdx) {
removeVnodes(oldCh, oldStartIdx, oldEndIdx)
}
}
Copy the code
Vue. Js v-Model implementation principle, and how to customize v-Model?
A: The component’s V-model is the syntactic sugar for the value+input method
<el-checkbox :value="" @input=""></el-checkbox>
<el-checkbox v-model="check"></el-checkbox>
Copy the code
You can redefine the meaning of the V-Model yourself
Vue.component('el-checkbox', {template:`<input type="checkbox" :checked="check" @change="$emit('change',$event.target.checked)">`.model: {prop:'check'.// Change the name of the default value
event:'change' // Change the default method name
},
props: {
check: Boolean}})Copy the code
Converts the component’s V-model default to value+input
const VueTemplateCompiler = require('vue-template-compiler');
const ele = VueTemplateCompiler.compile('<el-checkbox v-model="check"></el-checkbox>');
// with(this) {
// return _c('el-checkbox', {
// model: {
// value: (check),
// callback: function ($$v) {
// check = $$v
/ /},
// expression: "check"
/ /}
/ /})
// }
Copy the code
function transformModel (options, data: any) {
const prop = (options.model && options.model.prop) || 'value'
const event = (options.model && options.model.event) || 'input'; (data.attrs || (data.attrs = {}))[prop] = data.model.valueconst on = data.on || (data.on = {})
const existing = on[event]
const callback = data.model.callback
if (isDef(existing)) {
if (
Array.isArray(existing)
? existing.indexOf(callback) === -1: existing ! == callback ) { on[event] = [callback].concat(existing) } }else {
on[event] = callback
}
}
Copy the code
The native V-Model generates different events and attributes depending on the tag
const VueTemplateCompiler = require('vue-template-compiler');
const ele = VueTemplateCompiler.compile('<input v-model="value"/>');
/** with(this) { return _c('input', { directives: [{ name: "model", rawName: "v-model", value: (value), expression: "value" }], domProps: { "value": (value) }, on: { "input": function ($event) { if ($event.target.composing) return; value = $event.target.value } } }) } */
Copy the code
Compile-time: Different tags parse differently
if (el.component) {
genComponentModel(el, value, modifiers)
// component v-model doesn't need extra runtime
return false
} else if (tag === 'select') {
genSelect(el, value, modifiers)
} else if (tag === 'input' && type === 'checkbox') {
genCheckboxModel(el, value, modifiers)
} else if (tag === 'input' && type === 'radio') {
genRadioModel(el, value, modifiers)
} else if (tag === 'input' || tag === 'textarea') {
genDefaultModel(el, value, modifiers)
} else if(! config.isReservedTag(tag)) { genComponentModel(el, value, modifiers)// component v-model doesn't need extra runtime
return false
}
Copy the code
Runtime: Handles input method issues for elements
inserted (el, binding, vnode, oldVnode) {
if (vnode.tag === 'select') {
/ / # 6903
if(oldVnode.elm && ! oldVnode.elm._vOptions) { mergeVNodeHook(vnode,'postpatch'.() = > {
directive.componentUpdated(el, binding, vnode)
})
} else {
setSelected(el, binding, vnode.context)
}
el._vOptions = [].map.call(el.options, getValue)
} else if (vnode.tag === 'textarea' || isTextInputType(el.type)) {
el._vModifiers = binding.modifiers
if(! binding.modifiers.lazy) { el.addEventListener('compositionstart', onCompositionStart)
el.addEventListener('compositionend', onCompositionEnd)
// Safari < 10.2&uiWebView doesn't fire compositionEnd When
// switching focus before confirming composition choice
// this also fixes the issue where some browsers e.g. iOS Chrome
// fires "change" instead of "input" on autocomplete.
el.addEventListener('change', onCompositionEnd)
/* istanbul ignore if */
if (isIE9) {
el.vmodel = true}}}}Copy the code
The life cycle of vue.js components?
A: There are 8 stages: before/after creation, before/after loading, before/after updating, and before/after destruction
- Before/After creation: In the beforeCreate phase, the mount element EL and data object data of the VUE instance are both undefined and not initialized. In the Created phase, the vUE instance’s data object, Data, is available, but el is not
- Before/After loading: In the beforeMount phase, the vue instance’s $EL and data are initialized, but the previously virtual DOM node is still mounted, and data.message has not been replaced. In mounted phase, vue instance is mounted and data.message is successfully rendered.
- Before/After update: When data changes, the beforeUpdate and updated methods are triggered
- Before/after destroy: Changes to data do not trigger periodic functions after destroy, indicating that the vue instance has been unbound from event listening and the DOM structure still exists
To know when each life cycle is called
beforeCreate
After instance initialization, data Observer is called before.created
Called after the instance has been created. In this step, the instance completes the configuration of data Observer, property and method operations, and Watch/Event event callbacks. There’s no $el herebeforeMount
Called before the mount begins: The associated render function is called for the first time.mounted
El is newly createdvm.$el
Replace and mount the hook to the instance.beforeUpdate
Called when data is updated, before the virtual DOM is re-rendered and patched.updated
This hook is called after the virtual DOM is re-rendered and patched due to data changes.beforeDestroy
Called before instance destruction. At this step, the instance is still fully available.destroyed
Vue
Called after instance destruction. After the call,Vue
Everything indicated by the instance is unbound, all event listeners are removed, and all subinstances are destroyed. This hook is not called during server-side rendering.
What can be done inside each lifecycle
created
The instance has been created because it is the earliest trigger for the reason that some data, resource requests can be made.mounted
The instance is mounted and ready for some DOM manipulationbeforeUpdate
You can further change the state in this hook without triggering additional rerendering.updated
You can perform DOM-dependent operations. In most cases, however, you should avoid changing the state during this period, as this can lead to an infinite update loop. This hook is not called during server-side rendering.destroyed
You can perform optimization actions, empty timers, and unbind events
What is the VUE lifecycle?
A: The lifecycle of a Vue instance is the process from creation to destruction. The life cycle of a Vue is a series of processes from the beginning of creating, initializing data, compiling templates, mounting Dom, rendering, updating, rendering, and destroying.
What is the role of the VUE lifecycle?
A: It has multiple event hooks throughout its lifecycle, making it easier to form good logic when controlling the process of the entire Vue instance.
How many phases are there in the VUE life cycle?
A: It can be divided into 8 stages altogether: before/after creation, before/after loading, before/after update, and before/after destruction.
Which hooks are triggered the first time the page loads?
A: beforeCreate, created, beforeMount, and Mounted are triggered.
In what cycle is DOM rendering completed?
A: DOM rendering is done in Mounted
Describe the component rendering and update process?
A: When rendering a component, the child component’s constructor is built and instantiated using the vue.extend method. Finally, the mount is manually called $mount(). The patchVnode process is performed when the component is updated. The core is the Diff algorithm
How and in what ways do vue.js components communicate?
A:
- Communication between father and son Father -> son through
props
And children – > father$on, $emit
- How to get the parent component instance
$parent, $children
- Provide data child components in the parent component for consumption
Dojo.provide, inject
Ref
Calls a component property or method by getting an instanceEvent Bus
Implement cross-component communicationVuex
State management enables communication
1. Father-son correspondence
The parent component passes data to the child component via props, and the child component passes data to the parent component via emit events. These are the two most common implementations of parent-child communication.
This parent-child communication mode is a typical one-way data flow. The parent component passes data through props, and the child component cannot modify the data directly. Instead, it must send events to tell the parent component to modify the data.
The other two methods can also be implemented directly using the syntactic sugar V-model, which by default resolves to a prop named value and an event named input. This syntactic sugar approach is typical of bidirectional binding and is commonly used on UI controls, but at its core, events are used to let the parent component modify the data.
Of course we can also access the methods and data in the component instance by accessing the $parent or $children object.
$Listeners and.sync are also available if you are using Vue 2.3 and above.
The $Listeners attribute passes v-on event listeners from the parent component (without the.native modifier) to child components that can customize listeners by accessing $Listeners.
The.sync property is a syntactic sugar that makes it easy for children to communicate with their parents
<! -- Parent component --><input :value.sync="value" /><! -- This is equivalent to --><input :value="value" @update:value="v => value = v"></comp><! -- Subcomponent --><script>
this.$emit('update:value'.1)
</script>
Copy the code
2. Sibling component communication
In this case, you can find the child of the parent component, that is, this.$parent.$children.
3. Communicate across multi-level components
In this case, we can use the new API provide/inject in Vue 2.2. Although it is not recommended to use it directly in business, it is useful if it is used well.
Suppose you have A parent component A, and then A child component B that spans multiple levels
// Parent component A
export default {
provide: {
data: 1}}// Subcomponent B
export default {
inject: ['data'].mounted() {
// The parent component's data property can be obtained regardless of the number of layers
console.log(this.data) / / = > 1}}Copy the code
The ultimate solution to all communication problems
As long as you take the trouble, you can use Vuex or Event Bus to handle all of the above communication situations.
Why does Vue.js use asynchronous rendering?
A: Because without asynchronous updates, the current component is re-rendered each time the data is updated.
So for performance purposes. Vue will update the view asynchronously after this round of data update!
It’s kind of like throttling
update () {
/* istanbul ignore else */
if (this.lazy) {
this.dirty = true
} else if (this.sync) {
this.run()
} else {
queueWatcher(this); // When the data changes, watcher will be put into a queue for batch update}}export function queueWatcher (watcher: Watcher) {
const id = watcher.id // The same watcher is filtered
if (has[id] == null) {
has[id] = true
if(! flushing) { queue.push(watcher) }else {
let i = queue.length - 1
while (i > index && queue[i].id > watcher.id) {
i--
}
queue.splice(i + 1.0, watcher)
}
// queue the flush
if(! waiting) { waiting =true
if(process.env.NODE_ENV ! = ='production' && !config.async) {
flushSchedulerQueue()
return
}
nextTick(flushSchedulerQueue) // Call the nextTick method for batch updates}}}Copy the code
What is the difference between v-if and V-show in vue.js?
A:
v-if
Will not render the node of the current instruction if the condition is not truedom
The elementv-show
Just toggle the currentdom
Show or hide
V-show simply switches between display: None and display: block. Whatever the initial conditions are will be rendered, just switch CSS later, and the DOM will remain. So in general v-show has a higher initial rendering overhead, but the switching overhead is small and is better suited for frequently switched scenes.
V -if is used to talk about Vue low-level compilation. When the property is initially false, components will not be tinted until the condition is true, and switching the condition triggers destruction/mounting of components, so in general switching has a higher open pin and is more suitable for less frequent switching scenarios.
The v-IF based lazy rendering mechanism allows components to be rendered only when necessary, reducing the initial rendering overhead of the entire page.
Summary: v-if is rendered according to conditions, v-show is block or none of display;
const VueTemplateCompiler = require('vue-template-compiler');
let r1 = VueTemplateCompiler.compile(`<div v-if="true"><span v-for="i in 3">hello</span></div>`);
/** with(this) { return (true) ? _c('div', _l((3), function (i) { return _c('span', [_v("hello")]) }), 0) : _e() } */
Copy the code
const VueTemplateCompiler = require('vue-template-compiler');
let r2 = VueTemplateCompiler.compile(`<div v-show="true"></div>`);
/** with(this) { return _c('div', { directives: [{ name: "show", rawName: "v-show", value: (true), expression: "true" }] }) } */
/ / v - is the style definitions show operation in platforms/web/runtime/directives/show. Js
bind (el: any, { value }: VNodeDirective, vnode: VNodeWithData) {
vnode = locateNode(vnode)
const transition = vnode.data && vnode.data.transition
const originalDisplay = el.__vOriginalDisplay =
el.style.display === 'none' ? ' ' : el.style.display
if (value && transition) {
vnode.data.show = true
enter(vnode, () = > {
el.style.display = originalDisplay
})
} else {
el.style.display = value ? originalDisplay : 'none'}}Copy the code
Why can’t v-for and V-if be used together in vue. js?
A: V-for has a higher priority than v-if. If used continuously, v-if is added to every element, causing performance problems
const VueTemplateCompiler = require('vue-template-compiler');
let r1 = VueTemplateCompiler.compile(`<div v-if="false" v-for="i in 3">hello</div>`);
/** with(this) { return _l((3), function (i) { return (false) ? _c('div', [_v("hello")]) : _e() }) } */
console.log(r1.render);
Copy the code
Implement hash route and history route in vue. js?
A:
onhashchange
history.pushState
- Hash mode: In the browser, the symbol “#” is called a hash, and the characters after # are read with window.location.hash. Features: Hash is in the URL, but is not included in the HTTP request. Hash is used to instruct browser actions. It is useless for server security and does not reload pages.
- History mode: Istory uses new HTML5 features; Two new methods are provided: pushState(), replaceState() to modify the browser history stack, and popState events to listen for state changes
Vue. Js action is not mutation.
A:
mutation
Yes Data is updated synchronously (an internal check is performed to determine whether data is updated asynchronously)action
Asynchronous operation, can obtain data after the commissionmutation
Submit final data
What’s the difference between vue.js and React?
A: The same
Both support SSR, both have VDOM, componentized development, implementation of webComponents specification, data drive and so on
The difference between
Vue is a two-way data flow (vuex was introduced, of course, in order to manage component state with a single data flow), react is a one-way data flow. The VDOM of vue keeps track of each component’s dependencies and does not render the entire component tree. React Re-render all the child components whenever the state should be changed
The React. Js interview questions
React life cycle function?
A: Fiber was introduced in the V16 version. This mechanism affects part of the lifecycle calls to some extent, and two new apis are introduced to address the issue
In previous versions, if you had a complex composite component and changed the state of the uppermost component, the call stack would overcall the stack, and complicated operations in the middle would block the main thread for a long time, leading to a bad user experience. Fiber is essentially a virtual stack frame. The new scheduler schedules these frames according to their priority, changing the previous synchronous rendering to asynchronous rendering, and computing updates in segments without affecting the experience. React has its own logic for how to distinguish priorities. React pauses the update every 16 ms and returns to render the animation. For asynchronous rendering, there are now two stages: Reconciliation and commit. The former process can be interrupted, while the latter process cannot be paused and keeps updating the interface until it is complete.
Initialization phase
- GetDefaultProps: Gets the default properties of the instance
- GetInitialState: Gets the initialization state of each instance
- ComponentWillMount: Components are about to be loaded and rendered onto the page
- Render: This is where the component generates virtual DOM nodes
- OmponentDidMount: The component is actually loaded after
Running state
- ComponentWillReceiveProps: components that will receive calls to the property
- ShouldComponentUpdate: When the component receives a new property or state (it can return false, the number to receive)
- Render function will not be executed if the render call is not updated.
- ComponentWillUpdate: The component is about to update and cannot modify its properties and state
- Render: Component repainting
- ComponentDidUpdate: Components have been updated
Destruction of phase
- ComponentWillUnmount: Component is about to be destroyed
Since the Reconciliation phase can be interrupted, life cycle functions executed during the Reconciliation phase can be called multiple times, causing bugs. As a result, several functions called in the Reconciliation phase should be avoided except shouldComponentUpdate, and a new API was introduced in V16 to address this issue.
GetDerivedStateFromProps used to replace componentWillReceiveProps, this function can be in initialization and is invoked when the update
What do keys do in React?
A: Keys are an auxiliary identifier used by React to track which elements in a list are changed, added, or removed
During development, we need to ensure that an element’s key is unique among its siblings. In the React Diff algorithm, React uses the Key value of an element to determine whether the element is newly created or moved, thus reducing unnecessary element re-rendering. React also relies on keys to determine the relationship between elements and local state, so we should never ignore the importance of keys in conversion functions
What does refs do in React?
A:
- Refs is a handle to a DOM element or component instance that React provides us with secure access
- You can add a ref attribute to an element and then accept a handle to that element in the DOM tree in the callback function, which is returned as the first argument to the callback function
How does React Native have advantages over Native ios and Android?
A:
- 1. Performance comparable to native APP
- 2. Code in JavaScript, just learn the language
- 3. Most code can be shared between Android and IOS
- 4. Component development with high code reuse
- 5. Like writing web pages, modify the code can automatically refresh, do not need to slowly compile, save a lot of compile waiting time
- 6. Support hot update of APP without reinstalling APP
Disadvantages:
- The memory usage is relatively high
- The release is not stable, it is constantly updated, and there is no stable 1.0 release yet
What are the similarities and differences between props and state?
1. Any change to props or state causes the render to be rerendered.
2. Each can be initialized by the corresponding initialization function of its own component.
The difference between
The initial value of state comes from its own getInitalState (constructor) function; Props comes from the parent component or getDefaultProps itself (the former overrides the latter if the key is the same).
2. Modification method: State Can only be set in its own component, but cannot be changed by the parent component. Props can only be modified by the parent component, not by its own component.
3. For child components: props is a data flow that is passed from a parent component to a child component. This data flow can be passed to a descendant component. State represents the internal state of a component and can only exist in its own component.
Brief flux ideas?
A: The biggest feature of Flux is the “one-way flow” of data.
- User access to View
- The View emits the user’s Action
- Dispatcher receives Action requesting Store to update accordingly
- After the Store is updated, a “change” event is emitted
- View updates the page after receiving the “change” event
React: What’s wrong with react?
A:
- When JSX does expression judgment, it needs to be cast to Boolean strongly
If not used!! B will force the data type and print 0 in the page.
render() {
const b = 0;
return <div>
{
!!!!! B && <div> this is a text </div>
}
</div>
}
- Try not to use setState in componentWillReviceProps. If you must use setState, then you need to validate the end condition, otherwise infinite rerender will occur and the page will crash
- When adding a ref to a component, try not to use anonymous functions, because when the component is updated, the anonymous functions will be treated as a new prop. When the ref property receives the new function, react will empty the ref function first, that is, execute the ref function once using null as the callback parameter. The ref is then executed on the instance of the component, so when using anonymous functions to do ref, sometimes the attribute after the ref assignment will be null
- When traversing child nodes, do not pass in index as the component’s key
React Performance Optimization?
A:
- Override shouldComponentUpdate to avoid unnecessary DOM manipulation
- Use the Production version of react. Js
- Use keys to help React recognize minimal changes to all the child components in the list
In the shouldComponentUpdate function we can return a Boolean to determine if the current component needs to be new. This layer of code logic can be as simple as a shallow comparison of whether the current state is the same as the previous state, or a component update is triggered when a value is updated. A complete comparison of the current state to the previous state is generally not recommended, because component update triggers can be frequent, and such a complete comparison can be a bit costly and may not be worth the cost
Of course, if you really want to completely compare the current state to the previous state without affecting performance, it is possible to generate immutable objects by using libraries such as immutable or immer. This kind of library can improve the performance of large scale data, and once the data is changed, a new object will be generated, the comparison between the state is more convenient, but also recommended to read the source implementation of immer
For shallow comparisons, you can use PureComponent to implement shallow comparison state
class Test extends React.PureComponent {
render() {
return (
<div>
PureComponent
</div>)}}Copy the code
At this point you may consider that function components do not work in this way. If you are using versions later than 16.6.0, you can use react.Memo to do the same
const Test = React.memo(() = > (
<div>
PureComponent
</div>
))
Copy the code
In this way we can implement shouldComponentUpdate as a shallow comparison while still using function components
The React to monitor?
A:
Front-end monitoring is generally divided into three types, namely, page burying point, performance monitoring and exception monitoring.
In this chapter, we’ll cover some of these monitoring topics, but we won’t cover much of the code, just to give you an idea of how front-end monitoring can be implemented. After all, most companies are using third-party monitoring tools rather than building their own wheels
1 Page burying point
Page buried point should be the most frequently written monitoring, generally at least will monitor the following data:
- PV / UV
- The stay time
- Traffic sources
- The user interaction
For these kinds of statistics, the general implementation ideas can be roughly divided into two kinds, respectively for handwritten buried point and no buried point.
The first approach, which I believe is the most common, is to choose the data you want to monitor and write code where it fits in. There’s a lot of flexibility in this approach, but the only downside is that it’s a lot of work, and you have to plug in code everywhere you need to monitor.
The other no-burying method basically doesn’t require the developer to write a burying point by hand, but instead counts all events and reports them regularly. Although this method is not as complicated as the previous one, because all events are counted, the required data needs to be filtered out in the later stage.
2 Performance Monitoring
Performance monitoring is a great way to help developers understand how pages perform in various real-world environments.
For Performance monitoring, you can use the browser’s own Performance API to do this.
For performance monitoring, all you need to do is call
Performance. GetEntriesByType (‘ navigation ‘) this line of code. Yes, you read that right, with one line of code we can get all kinds of detailed performance information on the page
We can see that this line of code returns an array containing quite a bit of information from the time the data is transferred over the network to the time the page is loaded
3 Abnormal Monitoring
For exception monitoring, the following two types of monitoring are indispensable: code error reporting and interface exception reporting. For code execution errors, the usual approach is to use window.onerror to intercept the error. This method can intercept most detailed error messages, but there are exceptions
- Script error is displayed for cross-domain code execution errors. In this case we need to add the Crossorigin attribute to the Script tag
- For some browsers that may not display call stack information, stack recursion can be done with arguments.callee.caller
For asynchronous code, errors can be caught using a catch method. For example, a Promise can use a catch function directly, and async await can use a try catch
Note, however, that the code running online is compressed, and you need to generate the sourceMap file at package time for debugging
For caught errors that need to be uploaded to the server, a request can usually be made with the SRC of the IMG tag.
In addition, the interface exception is relatively simple, you can list the status code of the error. An error can be reported immediately when such a status code occurs. Interface exception reporting allows developers to quickly know which interfaces have a large number of reported errors, so that problems can be quickly repaired.
The React. Js communications?
Answer: 1. Father-son communication
The parent component passes data to the child component through props, and the child component passes data to the parent component by calling functions passed by the parent component. These two methods are the most common implementations of parent-child communication.
This parent-child communication mode is a typical one-way data flow. The parent component passes data through props, and the child component cannot modify the data directly. Instead, it must tell the parent component to modify the data by calling the functions of the parent component.
2. Sibling component communication
In this case, state and event functions can be managed through a common parent component. For example, one of the sibling components calls an event function passed by the parent component to modify the state in the parent component, which then passes the state to the other sibling
3. Communicate across multi-level components
If you are using version 16.3 or later, you can use the Context API for this situation
// Create Context, which can be passed in at the beginning
const StateContext = React.createContext()
class Parent extends React.Component {
render () {
return (
// Value is the value passed into the Context
<StateContext.Provider value='yck'>
<Child />
</StateContext.Provider>)}}class Child extends React.Component {
render () {
return (
<ThemeContext.Consumer>{context => (name is {context})}</ThemeContext.Consumer>); }}Copy the code
4. Any component
This can be done with Redux or Event Bus, and if you are not afraid to go to the trouble, you can use this method for all of the above communication situations.
React event mechanism?
A: React actually implements its own event mechanism, so consider the following code first
const Test = ({ list, handleClick }) => ({ list.map((item, index) => ( <span onClick={handleClick} key={index}>{index}</span> )) })
I’m sure you’ve written about this all the time, but have you ever considered whether the click event is tied to every tag? The fact is, of course, that events written on JSX are not bound to the corresponding REAL DOM, but rather all events are bound to the Document by means of an event broker. This approach not only reduces memory consumption, but also provides uniform subscription and removal of events during component mount destruction.
The events that bubble up to the document are not native browser events, but synthetic events implemented by React itself. So event.stopPropagation is invalid if we don’t want the event to bubble, event.preventDefault should be called instead
So what is the purpose of implementing synthetic events? In general, in my opinion, there are two advantages:
- Synthetic events first smoothes out compatibility issues between browsers, and this is a cross-browser native event wrapper that gives cross-browser development capabilities
- For native browser events, the browser creates an event object for the listener. If you have a lot of event listening, you will need to allocate a lot of event objects, causing high memory allocation problems. In the case of synthetic events, however, there is an event pool that manages their creation and destruction. When an event needs to be used, objects are reused from the pool. After the event callback is complete, the properties on the event object are destroyed so that the event object can be reused next time.
Tool interview questions
What is the difference between Git and SVN?
A: The biggest difference between Git and SVN is that Git is distributed while SVN is centralized. Therefore, we can no longer use SVN offline. If there is a problem with the server, there is no way to use SVN to submit our code.
A branch in SVN is a complete directory copy of the entire repository, whereas a branch in Git is a pointer to a commit, so creating a branch in Git is cheaper and changes in the branch do not affect other people. Branch changes to the SVN affect everyone.
SVN commands are simpler and easier to use than Git.
Git command that you use most often?
A:
Git git git git git git git git git git git git git git Git checkout -b [branch] // Create a new branch. Switch to the branch git status // to display the changed filesCopy the code
Git fetch and Git pull
A: Git Fetch simply downloads changes from a remote repository, not merges them with a local branch.
Git pull downloads the changes from the remote repository and merges them with the current branch.
Git rebase is a git merge.
A: Git merge and Git rebase are both used for branch merges. The key is how to handle commit records.
Git merge creates a new commit object, and both branches’ previous commit records point to this new commit. This method preserves the commit history of each previous branch.
Git rebase finds the first common commit ancestor of both branches, extracts all subsequent commits from the current branch, and adds this commit to the latest commit of the target branch. After this merge, the merge commit becomes a linear record.
Algorithmic interview questions
How does JavaScript evaluate the maximum and minimum value of an array?
A:
var arr = [6.4.1.8.2.11.23];
console.log(Math.max.apply(null, arr))
Copy the code
How to find the most frequently used words in an English article?
A:
function findMostWord(article) {
// Check the validity
if(! article)return;
// Parameter processing
article = article.trim().toLowerCase();
let wordList = article.match(/[a-z]+/g),
visited = [],
maxNum = 0,
maxWord = "";
article = "" + wordList.join("") + "";
// count the number of occurrences
wordList.forEach(function (item) {
if (visited.indexOf(item) < 0) {
let word = new RegExp("" + item + ""."g"),
num = article.match(word).length;
if(num > maxNum) { maxNum = num; maxWord = item; }}});return maxWord + "" + maxNum;
}
Copy the code
JavaScript bubble sort?
A: The basic idea of bubble sort is to compare adjacent elements in pairs and swap them in reverse order, so that each trip “floats” the smallest or largest elements to the top, eventually reaching complete order.
Code implementation:
function bubbleSort(arr) {
if (!Array.isArray(arr) || arr.length <= 1) return;
let lastIndex = arr.length - 1;
while (lastIndex > 0) { // The last element to swap is the first
let flag = true, k = lastIndex;
for (let j = 0; j < k; j++) {
if (arr[j] > arr[j + 1]) {
flag = false;
lastIndex = j; // Sets the position where the element was last swapped
[arr[j], arr[j+1]] = [arr[j+1], arr[j]]; }}if (flag) break; }}Copy the code
Bubble sort can be optimized in two ways.
One is the optimization of the outer loop, where we can record whether a swap has taken place in the current loop. If no swap has taken place, the sequence is already ordered. So we don’t need to execute the outer loop, we can just end it.
One is the optimization of the inner loop. We can record the position of the last element exchange in the current loop. The subsequent sequences of this position are already arranged, so there is no need to compare in the next loop.
When the sorted sequence is the sorted sequence, the optimal time complexity is O(n).
The average time complexity of bubble sort is O(n²), the worst time complexity is O(n²), the space complexity is O(1), it is stable sort.
JavaScript selection sort?
A: The basic idea of selective sorting is to select the smallest (or largest) element from the data elements to be sorted as the first element in each trip until all the elements are sorted.
In the implementation of the algorithm, the first position will be minimized by constant comparison and exchange during each trip to determine the minimum element, which is a time-consuming operation. In fact, it is easy to see that these swaps are meaningless until the current minimum element is fully determined. We can set a variable min to store only the index of the smallest element in each comparison. When the cycle is over, this variable stores the index of the smallest element in the current array, and then perform the swap operation.
Code implementation:
function selectSort(array) {
let length = array.length;
// If it is not an array or the array length is less than or equal to 1, it is returned without sorting
if (!Array.isArray(array) || length <= 1) return;
for (let i = 0; i < length - 1; i++) {
let minIndex = i; // Sets the minimum element index for the current loop
for (let j = i + 1; j < length; j++) {
// If the current element is smaller than the smallest element index, the smallest element index is updated
if(array[minIndex] > array[j]) { minIndex = j; }}// Swap the smallest element to the current position
// [array[i], array[minIndex]] = [array[minIndex], array[i]];
swap(array, i, minIndex);
}
return array;
}
// Swap the positions of two elements in the array
function swap(array, left, right) {
var temp = array[left];
array[left] = array[right];
array[right] = temp;
}
Copy the code
The time of selection sort is O(n ^ 2) regardless of whether the initial sequence is ordered or not.
The average time complexity of selection sort is O(n²), the worst time complexity is O(n²), and the space complexity is O(1), so it is not stable sort.
JavaScript insert sort?
A: The basic idea of direct insert sort is that each step inserts a record to be sorted into the previously sorted sequence until all the elements are inserted.
Insert sort core – poker thought: think of yourself in playing poker, pick up a, where it doesn’t matter, and then pick up a, smaller than the first, put on the left, continue to pick up, may be the middle number, inserted in the middle… . In turn,
Code implementation:
function insertSort(array) {
let length = array.length;
// If it is not an array or the array length is less than or equal to 1, it is returned without sorting
if (!Array.isArray(array) || length <= 1) return;
// The loop starts at 1, and position 0 is the default sorted sequence
for (let i = 1; i < length; i++) {
let temp = array[i]; // Save the current element to be sorted
let j = i;
// In the current sorted sequence, if it is larger than the element to be sorted, it moves backwards
while (j -1> =0 && array[j - 1] > temp) {
array[j] = array[j - 1];
j--;
}
// Insert the element at the found location
array[j] = temp;
}
return array;
}
Copy the code
When sorted sequence is sorted sequence, is the best time complexity O(n).
The average time complexity of insertion sort is O(n²), the worst time complexity is O(n²), the space complexity is O(1), it is stable sort.
JavaScript Hill sort?
A: The basic idea of Hill sort is to group arrays by certain increments of indices, and sort each group by direct insertion sort algorithm. As the increments decrease, each group contains more and more elements. When the increments decrease to 1, the whole array is exactly grouped and the algorithm terminates.
function hillSort(array) {
let length = array.length;
// If it is not an array or the array length is less than or equal to 1, it is returned without sorting
if (!Array.isArray(array) || length <= 1) return;
// The first layer determines the size of the increment, and each increment is halved in size
for (let gap = parseInt(length >> 1); gap >= 1; gap = parseInt(gap >> 1)) {
// Use insertion sort for each group, which is equivalent to replacing the insertion sort with n
for (let i = gap; i < length; i++) {
let temp = array[i];
let j = i;
while (j - gap >= 0&& array[j - gap] > temp) { array[j] = array[j - gap]; j -= gap; } array[j] = temp; }}return array;
}
Copy the code
Hill is the use of the insertion order for one of the best features of sorting sorted sequence effect, in the first sequence of chaotic sequence, the sequence is divided into multiple small grouping of radix sort, because the base of sorting is small, each time the effect of radix sort is better, and then gradually increase the incremental, to increase the size of the group, because every time is a sorted based on the results, So each time you can view it as a basic sort sequence, so you can maximize the benefits of insertion sort.
In simple terms, sorting is fast because each group starts with a small number of integers. Each group then contains more and more integers, but because the numbers are more and more ordered, the sorting is faster.
The time complexity of Hill sort varies according to the incremental sequence selected, but in general the time complexity is less than O(n^2).
Insertion sort is a stable sort, but hill sort is an unstable sort, because the same elements may be in different groups, so the position of the same elements may change.
The average time complexity of Hill sort is O(nlogn), the worst time complexity is O(n^s), and the space complexity is O(1), so it is not stable sort.
There was a staircase of ten steps, and you could only go up one or two steps for each step you took. And I want a program to figure out how many ways there are?
A: From our analysis, we can assume that we are only one step away from the 10th step. At this point, there are two situations, because each step only allows one or two steps, so it is 8 steps and 9 or 9 steps respectively. So the number of steps from 0 to 10 is the same thing as the number of steps from 0 to 9 plus the number of steps from 0 to 8. By analogy, we can obtain a recursion relationship, the end of which is marked by the number of steps from 0 to 1 and the number of steps from 0 to 2.
function getClimbingWays(n) {
if (n < 1) {
return 0;
}
if (n === 1) {
return 1;
}
if (n === 2) {
return 2;
}
return getClimbingWays(n - 1) + getClimbingWays(n - 2);
}
Copy the code
Comprehensive interview questions
What is the difference between let and VAR?
A:
- The let command does not have variable promotion and will cause an error if used before let
- If there are let and const commands in the block, a closed scope is formed
- Duplicate declarations are not allowed, so arguments cannot be redeclared inside functions
How to determine an array from JS?
A: The Instanceof method
The instanceof operator is an attribute used to test whether an object is in its stereotype chain stereotype constructor
var arr = [];
arr instanceof Array; // true
Copy the code
The constructor method
The constructor property returns a reference to the array function that created the object, which returns the corresponding constructor of the object
var arr = [];
arr.constructor == Array; //true
Copy the code
The easiest way
This is what jQuery is using
Object.prototype.toString.call(value) == '[object Array]'
// With this method, you can write a method that returns a data type
var isType = function (obj) {
return Object.prototype.toString.call(obj).slice(8, -1);
}
Copy the code
ES5 New method isArray()
var a = new Array(123);
var b = new Date(a);console.log(Array.isArray(a)); //true
console.log(Array.isArray(b)); //false
Copy the code
What performance optimizations did the project make?
A:
- Reduce the number of HTTP requests
- Reducing DNS queries
- Use the CDN
- Avoid redirection
- Lazy loading of images
- Reduce the DOM element count
- Reduce DOM manipulation
- Use external JavaScript and CSS
- Compress JavaScript, CSS, fonts, images, etc
- To optimize the CSS Sprite
- Using iconfont
- Font cutting
- Multi-domain distribution divides content into different domain names
- Minimize iframe use
- Avoid image SRC being empty
- Place the stylesheet in link
- Put the JavaScript at the bottom of the page
Browser cache?
A: Browser caches are divided into strong caches and negotiated caches. When a client requests a resource, the flow for retrieving the cache is as follows
The HTTP headers of this resource are used to determine whether it matches the strong cache. If yes, the cache resource is directly obtained from the local server without sending a request to the server.
When the strong cache does not match, the client sends a request to the server, which verifies that the resource matches the negotiated cache through another request header, called HTTP revalidation. If the resource matches, the server returns the request, but does not return the resource. Instead, it tells the client to fetch it directly from the cache. When the client receives the return, it retrieves the asset from the cache.
Strong and negotiated caches have in common that the server does not return the resource if the cache is hit; The difference is that strong caching does not send requests to the server, but negotiated caching does.
When the negotiation cache also dies, the server sends the resource back to the client.
When CTRL + F5 forces a page refresh, load it directly from the server, skipping strong cache and negotiated cache;
When F5 refreshes a web page, it skips the strong cache but checks the negotiated cache.
Strong cache
Expires (This field is the HTTP1.0 specification and is a gmT-formatted string of absolute time characters representing the expiration date of the cached resource.)
Cache-control :max-age (this field is the http1.1 specification, and the strong Cache uses its max-age value to determine the maximum lifetime of the Cache resource, which is in seconds)
Negotiate the cache
Last-modified (value is when the resource was Last updated and is returned with server response)
If-modified-since (Compares two times to determine whether the resource was Modified between requests. If not, the negotiated cache is hit.)
ETag (unique identifier for resource content, returned with server response)
If-none-match (The server compares the if-none-match in the request header with the ETag of the current resource to determine whether the resource has been modified between requests. If it has not been modified, it matches the negotiation cache
What SEO does the front end need to pay attention to?
A:
- Reasonable title, description, keywords: the weight of the search is reduced one by one, title
- Value to emphasize the key can, important keywords appear not more than 2 times, and to the front, different page title to not
- With; Description summarizes the content of the page, the length is appropriate, not excessive stacking keywords, different pages
- Description is different; Keywords list the key keywords
- Semantic HTML code that conforms to W3C specifications: semantic code makes it easy for search engines to understand web pages
- Important content HTML code at the front: search engines grab HTML order from top to bottom, some search engines to capture
- The length is limited to ensure that important content will be captured
- Do not output important content in JS: crawlers do not execute JS to retrieve content
- Use iframes sparingly: Search engines do not crawl iframes
- Alt must be used for non-decorative images
- Improve site speed: Site speed is an important indicator of search engine ranking
How does browser rendering work?
A: 1. The browser receives the HTML file and converts it into a DOM tree
When we open a web page, the browser requests the corresponding HTML file. Although we usually write code into JS, CSS, HTML files, or strings, computer hardware does not understand these strings, so the content transmitted across the network is actually 0 and 1 bytes of data. When the browser receives these bytes of data, it converts them into a string, which is the code we wrote.
After data is converted to strings, the browser first converts the strings into tokens through lexical analysis, a process called tokenization in lexical analysis.
So what is a tag? This is actually part of the compilation principle. Simply put, a tag is also a string, the smallest unit of code. This process breaks up the code into chunks and labels them so you can understand what the smallest units of code mean
When tokenization is complete, these tags are then converted into nodes, which are then built into a DOM tree based on previous relationships between different nodes
So that’s how the browser receives the HTML file from the web and then transforms it. Of course, when parsing the HTML file, the browser will also encounter CSS and JS files. At this point, the browser will also download and parse these files
2. Convert the CSS file to a CSSOM tree
The process of converting CSS to the CSSOM tree is very similar to the process in the previous section
During this process, the browser determines what the style of each node is, and this process can be very resource-intensive. Because styles can be set to a node or inherited. In this process, the browser recurses through the CSSOM tree and determines exactly what style the specific elements are.
If you don’t understand why it’s consuming resources, let me give you an example, right
<div>
<a> <span></span> </a>
</div>
<style>
span {
color: red;
}
div > a > span {
color: red;
}
</style>
Copy the code
In the first way, the browser just finds all the SPAN tabs on the page and sets the color, but in the second way, the browser first finds all the SPAN tabs, then the A TAB on the SPAN TAB, and then the div TAB. Then color span tags that match this condition, and the recursive process becomes complicated. So we should avoid writing too specific CSS selectors as much as possible, and add as few meaningless tags to THE HTML as possible to keep the hierarchy flat
3. Generate the render tree
Once we have generated the DOM tree and the CSSOM tree, we need to combine the two trees into a render tree
In this process, it is not as simple as merging the two. The render tree contains only the nodes to be displayed and the style information for those nodes. If a node is display: None, it will not be displayed in the render tree.
After the browser generates the render tree, it will make the layout (also called backflow) according to the render tree, and then call the GPU to draw, synthesize the layer, and display it on the screen. For this part of the content is too low-level, but also involved in the hardware related knowledge, here will not continue to expand the content.
21.2 Why is DOM manipulation Slow
You’ve all heard that manipulating the DOM sucks, but what’s the reason?
Because DOM is something that belongs in the rendering engine, and JS is something that belongs in the JS engine. When we manipulate the DOM through JS, which actually involves communication between two threads, there is bound to be some performance loss. Manipulating the DOM more than once means that threads are communicating with each other all the time, and manipulating the DOM can cause redraw backflow, which can lead to performance issues.
Classic interview question: Insert tens of thousands of DOM, how to achieve the page does not lag?
For this problem, first of all, we can’t insert tens of thousands of DOM all at once, which would definitely cause a lag, so the focus of the problem should be how to render the DOM in batches. Most of us can expect to just iterate on DOM insertion using a requestAnimationFrame, but there’s another way to solve this problem: Virtualized Scroller.
The principle of this technique is to render only the content in the visible area, not the non-visible area at all, and replace the rendered content in real time as the user scrolls
As you can see from the above figure, even though the list is long, there are only a few DOM elements rendered, and the DOM is updated in real time as we scroll through the page. This technique solves this classic interview problem
21.3 What happens when rendering is blocked
Rendering in the first place requires generating a rendering tree, so HTML and CSS will definitely block rendering. If you want to render faster, the more you should reduce the file size you need to render in the first place, flatten the hierarchy, and optimize the selector.
Then, when the browser parses the script tag, it pauses to build the DOM, and when it’s done, it picks up where it left off. That said, if you want the first screen to render as quickly as possible, you should not load JS files on the first screen, which is why it is recommended to place the script tag at the bottom of the body tag.
At the moment, of course, it’s not necessary to put the script tag at the bottom, as you can add defer or async properties to the script tag.
When the script tag adds the defer attribute, it means that the JS file will be downloaded in parallel, but will be executed sequentially after the HTML has been parsed, so you can place the script tag anywhere in this case.
Async property can be added to JS files that do not have any dependencies to indicate that JS file downloading and parsing will not block rendering.
21.4 Repaint and Reflow
Redraw and backflow occur frequently when we set the node style and can greatly affect performance.
- Redraw is when a node needs to change its appearance without affecting its layout, such as changing color
- Backflow is when layout or geometry properties need to be changed.
- Backflow must occur redraw, redraw does not necessarily cause backflow. The cost of backflow is much higher, and changing the child node in the parent node is likely to result in a series of backflows in the parent node.
The following actions can cause performance problems:
- Change window size
- Change the font
- Add or remove styles
- Text change
- Position or float
- The box model
And what a lot of people don’t know is that redraw and backflow are also related to Eventloop.
- When Eventloop completes Microtasks, it determines whether the document needs to be updated because the browser has a refresh rate of 60Hz and updates every 16.6ms.
- Then check whether there are resize or scroll events. If there are, events will be triggered. Therefore, resize and Scroll events will be triggered once at least 16ms, and have throttling function.
- Determines whether a Media Query is triggered
- Update the animation and send the event
- Check whether a full-screen operation event exists
- Execute the requestAnimationFrame callback
- Execute the IntersectionObserver callback. This method is used to determine whether elements are visible and can be used for lazy loading but is not compatible with updating the interface
- So that’s what you might do in one frame. If there is free time in a frame, the requestIdleCallback callback is executed
21.5 Reduce redrawing and reflow
- Use transform instead of top
<div class="test"></div>
<style>
.test {
position: absolute;
top: 10px;
width: 100px;
height: 100px;
background: red;
}
</style>
<script>
setTimeout(() = > {
// cause backflow
document.querySelector('.test').style.top = '100px'
}, 1000)
</script>
Copy the code
-
Use visibility instead of display: None, because the former will only cause redraw and the latter will cause backflow (changing the layout)
-
Do not put node property values in a loop as variables in the loop
for(let i = 0; i < 1000; i++) { // Fetching offsetTop causes backflow because the correct value needs to be fetched console.log(document.querySelector('.test').style.offsetTop) } Copy the code
-
Do not use the table layout, it is possible that a small change will cause the entire table to be rearranged
-
Select the speed of the animation implementation, the faster the animation, the more backflows, you can also choose to use requestAnimationFrame
-
CSS selectors match from right to left to avoid too many node hierarchies
-
Set nodes that are frequently redrawn or reflow as layers to prevent their rendering behavior from affecting other nodes. For the video TAB, for example, the browser automatically turns the node into a layer.
There are many ways to set the node as a layer. We can create new layers by using the following common attributes
will-change
Video and IFrame labels
There are a lot of pictures on a page (large e-commerce website), the loading is very slow, do you have some methods to optimize the loading of these pictures, to give users a better experience.
A:
- Image lazy loading, you can add a scrolling event in the invisible area of the page to judge the distance between the image position and the top of the browser and the distance between the page, if the former is less than the latter, the first loading.
- If it is a slide, album, etc., you can use the image preloading technology to download the first and last images of the current display.
- If the image is CSS image, you can use CSSsprite, SVGsprite, Iconfont, Base64 and other technologies.
- If the image is too large, you can use a specially encoded image that will load with a particularly compressed thumbnail to improve the user experience.
- If the image display area is smaller than the actual size of the image, compress the image on the server based on service requirements. The compressed image size is the same as that on the display.
Web page verification code is what, is to solve what security problems?
A:
- A public, fully automated program that distinguishes users from computers and human beings. Can prevent malicious crack password, brush tickets, forum irrigation
- Effectively prevent hackers to a specific registered users with a specific program to crack the way to continue the login attempt
My favorite interviewee
-
A solid
- From years of experience, those students who develop well have solid basic knowledge
- For example, you can’t do jQuery without JavaScript
- It would be nice to know the basics, because we’re going to have a lot of problems with non-front-end technology
-
Active thinking
- Students who are passive will make slow progress here
- You need to have your own ideas, not just complete tasks
-
The love of learning
- Front-end domain knowledge obsolesces quickly, so it’s best to learn and be exposed to new things frequently
-
There are deep
- When you encounter a problem, study the underlying causes rather than trying to get around them
- For example, tracking down a Bug and understanding its underlying cause
-
Have a vision
- Innovation often comes from the intersection of different disciplines, and the more fields you know, the more likely you are to come up with new ideas
Ok, this issue front end questions to share here, we see next period! Finally, I wish everyone can get the offer of dachang smoothly!