编程知识 cdmana.com

Summary of front-end high-frequency interview questions (the latest version in 2020), it is recommended to collect and absorb slowly! Continuous update

I have interviewed many front-end practitioners , The resume is plain and light , He can do what others can , It looks like you've got a little bit of everything ; Some would like to come over and talk to each other in person , Some refused ( If it is a position within the company that requires independent project completion , I put a lot of learning time in my resume DEMO project , There are no real online projects , This kind of resume is usually rejected ).

When we go to a company for an interview , The interviewer has a lot of initiative , The interviewer belongs to the attacker , Job seekers are on the defensive , We can't study everything very deeply , So it's the best way to develop your strengths and avoid your weaknesses , I recommend you to be a tent type person , Not the bucket type ; There are many jobs in the market , What we need to do is to find a career that suits our strengths !

Don't be tough with the interviewer during the interview , You can exaggerate yourself moderately , But don't think you're a technical cow , Just go crazy B; Interviewers are eager to find people with similar temperaments to work with , Even if you are one in a million , The interviewer feels uncomfortable working with you , So it's not too hard to say no to you .

If you come across the expected salary offer, Don't hesitate , Just promise to come down , But the time of entry , You can push it back a little bit , It can be in a week , Ten days later , During this period of time to continue the interview , At this time, the salary must be higher than what you have promised offer Pay for , If you meet more satisfied offer, Just what I promised offer To find the one you are most interested in .

Catalog

HTML Interview questions

CSS Interview questions

JavaScript Interview questions

Network communication interview questions

jQuery Interview questions

Vue.js Interview questions

React.js Interview questions

Tool interview questions

Algorithm interview questions

Comprehensive interview questions

My favorite interviewers


 


HTML Interview questions

HTML5 What's new ?

answer :1.HTML4 There are three types of declaration , Namely : Strict mode 、 Transition mode and Schema frameset ;

and HTML5 Because not SGML Subset , It only needs <!DOCTYPE> That's all right. :

2. Semantically better content tags .header/footer/article etc.

3. Audio 、 video API(audio,video)

4. The form controls :

HTML5 Have multiple new form input types . These new features provide better input control and validation .

  • color
  • date
  • datetime
  • datetime-local
  • email
  • month
  • number
  • range
  • search
  • tel
  • time
  • url
  • week

5.5 individual API- The local store , Long term storage of data  localStorage, More commonly used , Temporarily stored  sessionStorage, Automatically delete when the browser is closed , There are not many scenarios used in actual work .

canvas /Canvas,canvas,figure,figcaption.

Geography /Geolocation. Location API Allow the user to Web Applications provide their location . For privacy reasons , User permission is requested before reporting geographic location .

Drag release .HTML Drag release (Drag and drop) Interface enables applications to use drag and drop functionality in browsers . for example , Through these functions , Users can use the mouse to select draggable elements , Drag an element to a placeable element , And place these elements by releasing the mouse button . A translucent representation of a draggable element follows the mouse pointer during the drag operation .

Web Workers.webworker, websocket, Geolocation, When in HTML When the script is executed in the page , The state of the page is unresponsive , Until the script is finished .web worker It's running in the background JavaScript, Independent of other scripts , It doesn't affect the performance of the page . You can continue to do whatever you like : Click on 、 Select content and so on , And then web worker Running in the background .

Doctype do ⽤? How to distinguish strict pattern from hybrid pattern ? What do they mean ?

answer :

  • ⻚⾯ When loaded , link Will be loaded at the same time ,⽽ @imort ⻚⾯ When loaded , link Will be added at the same time
  • load ,⽽ @import lead ⽤ Of CSS Will wait ⻚⾯ Load after loading import Only in IE5 Only by doing so can we know
  • other ,⽽ link yes XHTML label ,⽆ compatibility link ⽅ The weight of the style ⾼ On @import The right to
  • heavy
  • <!DOCTYPE>  Declaration at ⽂ Top of the file ⾯, be in  <html>  Before the label . Tell browser's parser , ⽤ what ⽂ File type Specification to parse this ⽂ files
  • Strict pattern layout and JS The mode of operation is With this browser ⽀ Hold the most ⾼ Standard transport ⾏
  • In hybrid mode ,⻚⾯ With loose, backward compatible ⽅ It's a simple display . simulation ⽼ The browser's ⾏ In case ⽌ Site ⽆ Law ⼯ do . DOCTYPE Nonexistence or incorrect format can result in ⽂ Files are presented in hybrid mode

How to realize the communication between multiple tabs in the browser ?

call localstorge、cookies Wait for local storage ;

  • 1、 stay B You can use window.opener get A Page window Handle , Use this handle to call A Objects in the page , Functions, etc .
    • for example A Page definition js function onClosePageB, stay B The page can use window.opener.onClosePageB To call back .
  • 2、 Use  window.showModalDialog(sURL [, vArguments] [,sFeatures]) Open a new window . among vArguments Parameters can be used to pass parameters to the dialog box . The type of parameter passed is unlimited , Including arrays 、 Functions, etc . Dialog box through window.dialogArguments To get the parameters passed in .
  • 3、 If it's support HTML5 Words , Local storage is recommended (local storage), It supports an event method window.onstorage, As long as one of the windows modifies the local storage , Other cognate windows trigger this event .

summary :

  • WebSocket、SharedWorker;
  • You can also call localstorge、cookies Wait for local storage ;
  • localstorge In another browsing context 、 When modified or deleted , It will trigger an event ,
  • We're monitoring events , Control its value to communicate with page information ;
  • Be careful quirks:Safari Set... In traceless mode localstorge Value will be thrown QuotaExceededError It's abnormal ;

Method 1 : call localstorge

label 1:

<input id="name">
<input type="button" id="btn" value=" Submit ">
<script type="text/javascript">
    $(function(){
        $("#btn").click(function(){
           var name=$("#name").val();
            localStorage.setItem("name", name); // Store the information you need 
        });
   });
</script>

label 2:

$(function(){
    window.addEventListener("storage", function(event){
	   console.log(event.key + "=" + event.newValue);
    });     // Use storage Event monitoring add 、 modify 、 Delete action 
});

Method 2 : Use cookie+setInterval

Store the information to be delivered in cookie in , Read at regular intervals cookie Information , You can get the information you want to transfer at any time .

label 1:

$(function(){
    $("#btn").click(function(){
        var name=$("#name").val();
        document.cookie="name="+name;
    });
});

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);
});

⾏ What are the internal elements ? What are the block level elements ? empty (void) Elements have those ?⾏ Nei yuan What's the difference between a prime and a block level element ?

answer :

  • ⾏ The inner 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 elements : br,hr img input link meta
  • ⾏ Inner element cannot be set width ⾼, Not exclusive ⼀⾏
  • Block level elements can be set wide ⾼, Monopoly ⼀⾏

sketch ⼀ Next src And href The difference between ?

answer :

  • src ⽤ Replace current element on ,href⽤ At present ⽂ File and guide ⽤ Between resources ⽴ contact .
  • src yes source Abbreviation , Point to the location of external resources , The content pointed to will be embedded ⼊ To ⽂ Where is the current label in the file ; In the request src The resource it points to will be downloaded and should be ⽤ To ⽂ Inside the file , for example js Script ,img chart ⽚ and frame Equal elements
    • <script src ="js.js"></script>  When the browser resolves to the element , It's going to pause other
    • Downloading and processing of resources , Until the resource is loaded 、 compile 、 Of board ⾏ complete , chart ⽚ And frame elements
    • So it is , It is similar to embedding the pointed resource into ⼊ In the current label . That's why will js Script at the bottom
    • Ministry ⽽ Not the head
  • href yes Hypertext Reference Abbreviation , Point to ⽹ Location of network resources , build ⽴ And the current element ( Anchor point ) Or at present ⽂ files ( link ) Links between , If we were ⽂ Add
  • <link href="common.css" rel="stylesheet"/>  The browser will recognize the ⽂ The file is css ⽂ Pieces of , It will be and ⾏ Download resources and never stop ⽌ For the current ⽂ File processing . That's why it's suggested that ⽤ link ⽅ To load css ,⽽ Not to make ⽤ @import ⽅ type

cookies,sessionStorage,localStorage  The difference between ?

answer :

  • cookie The website is stored in the user's local terminal to identify the user (Client Side) The data on the ( Usually encrypted ).
  • cookie Data is always in the same source http Carry... In the request ( Even if you don't need ), Remember to pass it back and forth between the browser and the server .
  • sessionStorage and localStorage It doesn't automatically send data to the server , Save locally only .

Storage size

  • cookie Data size cannot exceed 4k.
  • sessionStorage and localStorage Although there are also storage size limitations , But more than cookie Much more , You can achieve 5M Or bigger .

There is a time

  • localStorage Store persistent data , Data will not be lost after the browser is closed unless data is actively deleted ;
  • sessionStorage Data is automatically deleted when the current browser window is closed .
  • cookie Set up cookie Valid until expiration date , Even if the window or browser is closed

HTML5 The use and principle of offline storage ?

answer :

Similar storage

localStorage Long term data storage , Data will not be lost after browser is closed ; sessionStorage Data is automatically deleted when the browser is closed .

Offline storage

Two ways

  • HTML5 Offline storage of .appcache file 【 abandoned 】
  • service-worker  Standards for

HTML5 Offline storage of .appcache file 【 abandoned 】

When the user is not connected to the Internet , You can access the site or application normally , When a user is connected to the Internet , Update the cache file on the user's machine .

principle :HTML5 The offline storage of is based on a new .appcache File caching mechanism ( It's not storage technology ), Store resources offline through the parsing list on this file , These resources will be like cookie The same is stored down .

Then when the network is offline , The browser will display the page by the data stored offline .

How to use

  • 1、 The page head adds a... As follows manifest Properties of
  • 2、 stay cache.manifest File writing, offline storage resources

    CACHE MANIFEST
    #v0.11
    CACHE:
    js/app.js
    css/style.css
    NETWORK:
    resourse/logo.png
    FALLBACK:
    / /offline.html

     

  • 3、 When offline , operation window.applicationCache Implement the requirements .

service-worker

You can refer to

How to deal with it Mobile 1px By Render into 2px problem ?

answer :

meta In the tag viewport attribute ,initial-scale Set to 1

rem Follow the design standard , Plus use transfrome Of scale(0.5) Just double it ; 2 Global processing

meta In the tag viewport attribute ,initial-scale Set to 0.5

rem Follow the standard of design draft

explain

UI When designers design , Painted 1px( Real pixels ) It's actually 0.5px(css) The lines or borders of . But he doesn't think so , He thinks what he painted is 1px Line , Because the size of his drawing is the size of the screen 2 times . Let's say the width of the retina is 320x480 wide , But the actual size is 640x960 wide , Designers must design drawings according to 640x960 The design of the . But when front-end engineers write code , all css This is the 320x480 Written , Write 1px(css), Browser automatically becomes 2px( Real pixels ).

So why can't the front-end engineer write directly 0.5px(css) Well ? Because it was written in the old system 0.5px(css) Words , Will be interpreted by the browser as 0px(css), There will be no borders . So it can only be written as 1px(css), It's actually shown on the screen by the designer 1px( Real pixels ) Of 2 Times as wide as that , It's too thick for designers, so , It's not the same as his design . In the new system , It has begun to gradually support 0.5px(css) This kind of writing . So if the designer designs a big picture 1px( Real pixels ) Of the line , Front end engineer directly divided by 2, Write 0.5px(css) Just fine .

Another explanation

The fact is that it's not getting thicker , Namely css In the unit 1px, about dpr by 2 The equipment , The minimum value it can actually display is 0.5px.

What the designer said 1px It's for the physical pixels of the device , The conversion css Pixels are 0.5px.

One sentence summary ,background:1px solid black It's the same size on any screen , however retina The screen can show a smaller border than this , And then designers don't like it , Let you change ...

How does the browser render the page ?

answer :

analysis HTML file , establish DOM Trees

From top to bottom , Encounter any style (link、style) With scripts (script) It's all clogging up ( External styles do not block subsequent loading of external scripts ).

analysis CSS

priority : Browser default settings < User Settings < External style < inline style <HTML Medium style style ;

Build the render tree

take CSS And DOM Merge , Build the render tree (Render Tree)

Layout and drawing

Layout and drawing , Repaint (repaint) And rearrangement (reflow)

How to write high performance HTML?

answer :

Avoid using Iframe

Iframe It's also called inline frame, You can put a HTML The document is embedded in another document . Use iframe The advantage is that the embedded document can be completely independent of its parent document , With this feature, we can usually make browsers simulate multithreading , It should be noted that the iframe Does not increase the number of parallel downloads under the same domain name , A browser always shares a browser level connection pool with a connection to a domain name , Even across windows or across tabs , This is true in all major browsers . Because of this, it makes iframe The benefits are greatly reduced .

During page loading iframe Element blocks the parent document onload Event triggering , And developers usually do it in onload Initialize when event is triggered UI operation . for example , Set the focus of the login area . Because users are used to waiting for this operation , So as much as possible onload It's very important to trigger events to shorten the user's waiting time . In addition, developers will bind some important behaviors to unload Incident , Unfortunately, in some browsers , Only when onload After event triggering unload Event to trigger , If onload The event was not triggered for a long time , And the user has left the current page , that unload Events will never be triggered . Is there a plan to make onload Events are not iframe Is it blocked ? There is a simple solution to avoid onload Events are blocked , Use JavaScript Dynamic loading iframe Element or dynamic settings iframe Of src attribute :

<iframe id=iframe1 ></iframe>
document.getElementById(‘iframe1’).setAttribute(‘src’, ‘url’);

But it's only available in advanced browsers Effective in , about Internet Explorer 8 Browsers and below are not valid . Besides, we have to know iframe Is one of the most resource consuming elements in a document , stay Steve Souders tests , Load... Separately in the test page 100 individual A、DIV、SCRIPT、STYLE and IFRAME Elements , And they are in Chrome、Firefox、Internet Explorer、Opera、Safari Running on 10 Time . It turns out to create iframe Element is more expensive than creating other types of DOM The elements should be high 1~2 An order of magnitude . All in the test DOM The elements are empty , For example, loading large scripts or style blocks may be better than loading some iframe Elements take longer , But from the benchmark results , Even if it's empty iframe, It's also very expensive , Whereas iframe The high cost of , We should try to avoid using it . Especially for mobile devices , For most of the time, there are only a few CPU With the memory case , We should avoid using iframe.

Avoid empty link properties

Empty link properties refer to img、link、script、ifrrame Elemental src or href Property is set , But the property is empty . Such as <img src=''>, We created a picture , And temporarily set the address of the picture to be empty , Hope to modify it dynamically in the future . But even if the image's address is empty , The browser will still request an empty address by default :

  • Internet Explorer 8 And below are only available in img There is a problem with the type element ,IE Will be able to img The empty address of is resolved to the directory address of the current page address . for example : If the current page address is  http://example.com/dir/page.html,IE  The null address will be resolved to  http://example.com/dir/  Address and request .
  • Earlier versions of Webkit Kernel browser And Firefox The empty address will be resolved to the address of the current page . If there are multiple empty link attribute elements in the page , The server of the current page will be requested multiple times , Increase the load on the server . Compared with desktop browser, it is more active to update and upgrade the kernel , The question is ios And android The problem may be serious in the mobile browser of the system .
  • Fortunately, all mainstream browsers face iframe Of src When the property is empty , The null address will be resolved to about:blank Address , It doesn't make extra requests to the server .

Avoid deep nesting of nodes

Deep nested nodes often need more memory to initialize the build , And it's slower to traverse nodes , This is similar to browser building DOM It's about the mechanism of the document . For example, the following HTML Code :

<html>
<body>
<p>
Hello World
</p>
<div> <img src="example.png"/></div>
</body>
</html>

Through the browser HTML Parsing of parser , The browser will put the whole HTML The structure of the document is stored as DOM Tree structure . As the document nodes are nested deeper , Built DOM The deeper the tree level .

cut HTML Document size

The most obvious way to increase download speed is to reduce the size of the file , In particular, compression is embedded in the HTML In document JavaScript and CSS Code , This makes the page much smaller . Besides, reduce HTML Document size can also be taken in the following ways :

  • Delete HTM Blank spaces, blank lines and comments where the document has no effect on the execution result
  • avoid Table Layout
  • Use HTML5

Explicitly specify the document character set

HTML Specify the character set at the beginning of the page , Help the browser to start parsing immediately HTML Code .HTML A document is usually parsed as a sequence of strings with character set encoding information through internet delivery . The character set is encoded in HTTP In the response header , perhaps HTML The mark specifies . According to the character set obtained by the browser , Parse the encoding into characters that can be displayed on the screen . If the browser doesn't know the coded character set of the page , Usually before executing scripts and rendering pages , Cache the byte stream , Then search for the character set that can be parsed , Or parse the page code with the default character set , This can lead to unnecessary consumption of time . In order to avoid browsers spending time searching for the right character set to decode , So it's best to always explicitly specify the page character set in the document .

Explicitly set the width and height of the picture

When the browser loads the page's HTML Code , Sometimes you need to locate the page layout before the image download is complete .

If HTML There is no specified size in the picture in ( Width and height ), Or when the size described in the code does not match the size of the actual picture , The browser needs to wait until the image is downloaded “ to flash back ” The picture is displayed again , It takes extra time .

therefore , It's best to specify the size of each image on the page , Whether it's on the page HTML Inside <img>  label , Still CSS in .

<img src="hello.png" width="400" height="300">

Avoid script blocking loading

When the browser is parsing the regular script When labeling , It needs to wait script The download , Then parse and execute , And the subsequent HTML Code can only wait . To avoid blocking the load , Step to the end of the document , If you put script Label inserted in body Before ending the label :

<script src="example.js" ></script>
</body>

iframe Advantages and disadvantages ?

answer :

  • iframe Will block the main page Onload event ;
  • iframe Share connection pool with main page , And browsers have restrictions on connections to the same domain , So it will affect the parallel loading of the page .
  • Use iframe These two shortcomings need to be considered before . If needed iframe, It's better to go through javascript Dynamic to iframe add to src Property value , This can bypass the above two problems .

Canvas and SVG What is the difference between graphics ?

answer :Canvas and SVG Can be drawn on the browser .

SVG Canvas Memory after drawing , In other words, any use SVG All shapes drawn can be memorized and manipulated , The browser can be displayed again Canvas It is forgotten after drawing , Once it's done, you can't access pixels and manipulate it SVG For creating graphics, for example CAD The software is good , Once something is drawn , Users want to operate it Canvas It is used to draw and forget the field paintings similar to animation and games .

For later operation ,SVG You need to record the coordinates , So it's slow .

Because I didn't remember the task of future things , therefore Canvas faster .

We can use the related event processing of drawing objects, we can't use the related event processing of drawing objects , Because we don't have their reference resolution independent resolution dependence

  • SVG Does not belong to html5 Proprietary content , stay html5 There was before SVG.
  • SVG The file extension is ”.svg”.
  • SVG The drawn image is magnified without degradation of image quality .
  • SVG Images often make small icons and dynamic renderings in web pages .

Chat meta label ?

answer : The core

Some meta information provided to the page ( name / It's worth it ), be conducive to SEO.

Property value

name

name / The name of the value pair .author、description、keywords、generator、revised、others. hold content Property is associated with a name .

http-equiv

No, name when , The value of this property is taken .content-type、expires、refresh、set-cookie. hold content Attribute is associated with http Head

content

name / The value of the right , It can be any valid string . Always be with name Attribute or http-equiv Properties together

scheme

Used to specify the scheme to be used to translate attribute values .

 

CSS Interview questions

CSS3 What's new ?

answer :

  • New variety CSS Selectors (: not(.input): all class No “input” The node of )
  • Round corners (border-radius:8px)
  • Multi column layout (multi-column layout)
  • Shadows and reflections (Shadow\Reflect)
  • Text Effect (text-shadow、)
  • Text rendering (Text-decoration)
  • Linear gradient (gradient)
  • rotate (transform)
  • Added rotation , The zoom , location , tilt , Animation , Multi background
  • transform:scale(0.85,0.90) translate(0px,-30px) skew(-9deg,0deg) Animation:

Clear floating ⼏ Kind of ⽅ type , various ⾃ Advantages and disadvantages ?

answer :

  • ⽗ level div Definition height
  • Blank at the end div label clear:both
  • ⽗ level div Define pseudo class :after and zoom
  • ⽗ level div Definition overflow:hidden
  • ⽗ level div Also floating , You need to define the width
  • Add... At the end br label clear:both
  • ⽐ The better part is 3 Kind of ⽅ type , Many ⽹ All the stations are like this ⽤

Please explain CSS3 Of Flexbox( Elastic box layout model )?

answer : Set to Flex After the layout ( display: flex;), The child element float、clear and vertical-align Property will fail .

use Flex Elements of layout , be called Flex Containers (flex container), abbreviation ” Containers ”.

All its child elements automatically become container members , be called Flex project (flex item), abbreviation ” project ”.

The container has two axes by default : Horizontal spindle (main axis) And the vertical cross axis (cross axis).

Starting position of spindle ( The intersection with the border ) be called main start, The ending position is called main end; The starting position of the cross axis is called cross start, The ending position is called cross end.

Items are arranged along the main axis by default . The spindle space occupied by a single project is called main size, The cross axis space occupied is called cross size.

Properties of the container

following 6 Properties are set on the container (justify-content and align-items、flex-wrap:wrap Most commonly used ).

  • justify-content: Defines the alignment of the item on the spindle . It may take 5 It's worth
    • center:  In the middle
    • flex-start( The default value is ): Align left
    • flex-end: Right alignment
    • space-between: full-justified , The intervals between the items are all equal .
    • space-around: The spacing between each item is equal . therefore , 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 may take 5 It's worth .
    • center: Align the midpoint of the intersecting axis .
    • flex-start: Align the starting points of the intersecting axes .
    • flex-end: The ends of the intersecting axes are aligned .
    • baseline:  Baseline alignment of the first line of text for the project .
    • stretch( The default value is ): If the project is not set to height or set to auto, Will fill the entire container .
  • flex-flow:flex-flow The attribute is flex-direction Properties and flex-wrap Attribute shorthand , The default value is row nowrap.
  • flex-direction: Property determines the direction of the spindle ( That is, the arrangement direction of the project );
    • row( The default value is ): The principal axis is horizontal , The starting point is on the left .
    • row-reverse: The principal axis is horizontal , The starting point is on the right .
    • column: The principal axis is perpendicular , The starting point is at the top .
    • column-reverse: The principal axis is perpendicular , Starting edge .
  • flex-wrap: By default , The projects are all in one line ( also called ” axis ”) On .flex-wrap Attribute definitions , If an axis doesn't line up , How to wrap .
    • It may take three values .
    • (1)nowrap( Default ): Don't wrap .
    • (2)wrap: Line break , The first row is at the top .【 This property is often used with 】
    • (3)wrap-reverse: Line break , The first row is at the bottom .
  • align-content: Property defines the alignment of multiple axes . If the project has only one axis , This property does not work
    • flex-start: Align with the starting point of the intersecting axis .
    • flex-end: Align with the end of the cross axis .
    • center: Align with the midpoint of the intersecting axis .
    • space-between: Align with both ends of the cross axis , The average distribution of spacing between axes .
    • space-around: The spacing between each axis is equal . therefore , The spacing between the axes is twice as large as the spacing between the axes and the borders .
    • stretch( The default value is ): The axis occupies the entire cross axis .

Project attribute summary

following 6 Properties are set on the project .(align-self、flex、order)

  • align-self
    • Property allows a single item to have a different alignment than other items , covering align-items attribute . The default value is auto, Represents the... That inherits the parent element align-items attribute , If there is no parent element , Is equivalent to stretch; This attribute may take 6 It's worth , except auto, Everything else goes with align-items The attributes are exactly the same .
    • auto / flex-start / flex-end / center / baseline / stretch;
  • flex
    • The attribute is flex-grow, flex-shrink  and  flex-basis Abbreviation , The default value is 0 1 auto. The last two properties are optional . This property has two shortcut values :auto (1 1 auto)  and  none (0 0 auto). It is recommended to use this property first , Instead of writing three separate attributes , Because the browser will calculate the relevant value .
  • order
    • Property defines the order in which items are arranged . The smaller the numerical , The further up the line , The default is 0.
  • flex-grow
    • Attribute defines the magnification of the item , The default is 0, That is, if there is any remaining space , And don't zoom in . If all of the items flex-grow Attributes are 1, Then they will divide the remaining space equally ( If any ). If a project flex-grow The attribute is 2, Everything else 1, Then the former will occupy twice as much space as the others .
  • flex-shrink
    • flex-shrink Attribute defines the reduction ratio of the project , The default is 1, That is, if there is not enough space , The project will shrink . If all of the items flex-shrink Attributes are 1, When space runs out , I'm going to scale it down . If a project flex-shrink The attribute is 0, Everything else 1, When there is not enough space , The former does not shrink . Negative values are not valid for this property .
  • flex-basis
    • flex-basis Property defines before allocating extra space , Spindle space occupied by the project (main size). Browser according to this property , Calculate if the spindle has extra space . Its default value is auto, The original size of the project . It can be set to follow width or height Property is the same value ( such as 350px), Then the project will occupy a fixed space .

Explain the down float and how it works ? Tips for clearing floats ?

answer : Floating element out of document stream , Do not occupy space .

Floating element touches the border containing it or the border of floating element

Use empty tags to clear floats

This method is to add an empty tag after all floating tags   Definition css clear:both.  The disadvantage is to add meaningless labels .

Use overflow

Add... To the parent tag that contains the floating element css attribute  overflow:auto; zoom:1; zoom:1 For compatibility IE6.

Bring in style sheets CSS There are several ways ? What are the differences ? What is the priority ?

answer : stay HTML There are four ways to define CSS:

  • inline( Inline , Also known as in line style )、
  • embedding( The embedded )、
  • linking( External reference )
  • Stylesheet import (@import ).

detailed

  • One : Inline / Inline style : Use this property to specify the style directly , Of course , This style can only be used for the content of the element , It doesn't work for another element with the same name .
  • Two : The embedded (style): The user can be in HTML Document header defines multiple style Elements , Implement multiple style sheets .
  • 3、 ... and : External reference (link)

    • ① Style sheets can be shared among multiple documents , For larger websites , take CSS The style definition is a separate document , It can effectively improve the efficiency , And conducive to the maintenance of website style .
    • ② You can change the style sheet , Without change HTML file , This is also related to HTML The principle of separating language content from form is consistent .
    • ③ You can choose to load style sheets based on the media .
  • Four : Stylesheet import :@import url(“css/base.css”);

priority : Nearby principle

Inline > embedded > External reference > Stylesheet import

What is responsive design ? What is the basic principle of responsive design ?

answer : Responsive design , A website can be compatible with multiple terminals —— Instead of making a specific version for each terminal .

advantage

  • It is flexible to face different resolution devices
  • It can quickly solve the problem of multi device display adaptation

shortcoming

Compatible with all kinds of equipment , inefficiency

The code is cumbersome , There will be hidden useless elements , Longer load time

In fact, it's a compromise design solution , The best effect can not be achieved due to many factors

To some extent, it has changed the original layout structure of the website , There will be user confusion

【 Through these three steps , You can definitely understand the basic principles of responsive design and media query】

First step . Meta  label

To fit the screen , Most mobile browsers put HTML Page zooms to the width of the device screen . You can use meta Labeled viewport Property to set . The following code tells the browser to use the device screen width as the width of the content , And ignore the initial width setting . This code is written in  <head> Inside

<meta name="viewport" content="width=device-width, initial-scale=1.0">

IE8 Browsers and below do not support media query. You can use media-queries.js  or  respond.js . such IE Can support media query 了 .

<!--[if lt IE 9]> <script src="http://css3-mediaqueries-js.googlecode.com/svn/trunk/css3-mediaqueries.js"></script> <![endif]-->

The second step . HTML  structure

In this case , Yes header、content、sidebar and footer Such as the basic page layout .

header  There is a fixed height 180px,content  The width of the container is 600px,sidebar The width of 300px.

The third step . Media Queries

CSS3 media query  The key to responsive Web Design . It's like a if sentence , Tell the browser how to load a web page according to a specific screen width .

If the screen window is smaller than 980px, The rules come into effect . Set the width of the container as a percentage instead of pixels , It's more flexible .

If the document width is less than  300  Pixels modify the background presentation (background-color):

@media screen and (max-width: 300px) {
    body {
        background-color:lightblue;
    }
}

In pure CSS What is the principle of creating a triangle ?

answer : The principle of equipartition

At right angles to the rectangle , The pattern of the two sides should be divided equally

Like the upper left corner  border-top  and  border-left  We should divide the styles equally

If border-left  Colorless and transparent , border-top colored ,  One will come out 45 The sharp angle of degree

Let's talk about the box model ?

answer : It's simple , But it's hard to say , You can extend the , The deeper the answer , Wider , The more points you add

Content +padding+border+margin Say it again , And then the wind turned , Say if on the mobile end , This box model is not very suitable for development , It is best to box-sizing: border-box; Property change the box model ;

After writing this property, the width will include border, Because the mobile terminal mainly uses percentage , It's impossible to control precisely by pixels , If you let two screens 50% Of div side by side , And these two div also border and padding, The original box model couldn't do it , You have to use this css You can change the attributes of , But there is a problem ;

use inline-block Let two div Side by side , There will be a blank character in the middle , And write the newline code in one line , Or use font-size:0; To solve

Two box models

css3 It defines box-sizing attribute ; Application in mobile terminal ;

  • padding and margin The short form of
  • margin In the middle of the two DIV Method ;(margin:0 auto; And negative margin Writing )
  • margin Compatibility problem ,IE6img There is a blank below ;
  • border Of CSS3 New properties ;
  • border How to write triangles ;

Yes BFC The normative understanding of ?

answer :(W3C CSS 2.1  A concept in the specification , It determines how elements position their content , And with other elements   Systems and interactions .)

BFC, Block level formatting context , One creates a new BFC The boxes of are arranged independently , The style of the child elements in the box will not affect the external elements

. In the same  BFC  Two adjacent blocks in The stage box is in the vertical direction ( It has something to do with the direction of the layout ) Of  margin  There will be folding .

A page is made up of many Box Composed of , The type and display attribute , It's decided Box The type of .

Different types of Box, Will participate in different Formatting Context( The container that determines how to render the document ), therefore Box The elements inside are rendered in different ways , in other words BFC The inner elements and the outer elements don't affect each other .

Why do you say position absolute  Follow float  Affect performance ?

answer :position: absolute Will be completely detached from the document flow

No longer in z-index:0 Layer keeps the placeholder , Its left、top、right、bottom The value is set relative to the nearest position position: relative or position: absolute The ancestral element of ;

If none of the ancestor elements are set position: relative or position: absolute, So it's relative to body Elements .

float It can also change the document flow

The difference is ,float Attributes do not let elements “ Go up ” To another z-index layer , It still keeps the elements in the z-index:0 Layer arrangement ,float Unlike position: relative and position: absolute like that , It can't go through left、top、right、bottom Attributes precisely control the coordinates of elements , It can only pass through float:left and float:right To control the elements in the same layer “ Left floating ” and “ Right floating ”.float Will change the normal document flow arrangement , Affect the surrounding elements .

Another interesting thing is that position: absolute and float Will implicitly change display type , No matter what type of element it was before (display:none With the exception of ), As long as it's set position: absolute or float Any one of , Will let the element with display:inline-block How to display : You can set the length and width , The default width does not occupy the parent element .

Even if we set the display display:inline perhaps display:block, And it still doesn't work (float stay IE6 Double margins below bug It's by adding display:inline To solve the ).

It is worth noting that ,position: relative But it doesn't change display The type of .

position The attribute is absolute or fixed The elements of , Rearrangement costs less , Because you don't have to think about how it affects other elements

This rule can be interpreted : Why try to use Position:absolute; instead of float To float the elements

JS Why is it on the bottom ,CSS Why put it on it ?

answer : The browser parses from top to bottom html file .

take  css  Put the file in the head , css  Files can be loaded first . Avoid loading first  body  Content , Causes the page to start with a disordered style , And then it flashes .

take  javascript  The file is at the bottom because : if

take  javascript  Files in  head  Inside , It means you have to wait for all of them  javascript  The code is   download 、 Parsing and execution complete   After that, the content of the page will be presented .

This will cause a significant delay in rendering the page , The window is blank .

In order to avoid such a problem, it will generally be all  javascript  Files in  body  After the page content in the element .

 

Problems caused by floating elements and solutions ?

answer :

  • The height of the parent element cannot be extended , Affects elements of the same level as the parent element
  • Non floating elements of the same level as floating elements follow
  • If it wasn't for the first element to float , Then the elements before the element also need to float , Otherwise, it will affect the structure of page display

Extra label method

<div style="clear:both;"></div>

shortcoming : But this method will add extra tags to make HTML The structure doesn't look simple enough .

Use after Pseudo elements

#parent:after{
    content : ".";
    height : 0;
    visibility : hidden;
    display : block;
    clear : both;
}

The parent element is also set to float

shortcoming : The layout of elements adjacent to the parent element will be affected , It can't float all the way to body, It is not recommended to use  

Set up overflow by hidden perhaps auto

CSS A summary of the browser compatibility issues of :

answer : So called browser compatibility issues , Because different browsers have different parsing of the same code , Cause the page display effect is not unified .

in the majority of cases , Our need is , No matter what browser users use to view our website or log in to our system , Should be a unified display effect .

except IE6 and 7 Of itself bug, Other browsers BUG Very few . If you understand every sentence CSS It means , Write code in a standard way , It's very rare that bug.

Take a very simple example , A lot of people float:left after , worry IE6 The double margin bug, It doesn't matter , Add display:inline. In fact, this is wrong . You need to find out IE6 The double margin bug How did it come about :

The floating direction has the same direction margin value , That's what's going to happen bug. So if it's just floating , This is not going to happen bug Of .

Browser compatibility problem 1 : The default external patch and internal patch are different for different browsers

Symptoms of the problem : Just a few labels , Without style control , Respective margin  and padding Big difference .

Solution :CSS in  *{margin:0;padding:0;}

remarks : This is the most common and easy to solve browser compatibility problem , Almost all CSS Wildcards are used at the beginning of the file * To set the internal and external patches of each tag are 0.

Browser compatibility 2 : Block attribute label float after , There's another wild one margin Under the circumstances , stay IE6 Show margin Bigger than the setting

Symptoms of the problem : The common symptom is IE6 The one behind the middle is pushed to the next line

Frequency :90%( A little bit more complex page will encounter ,float The most common browser compatibility problem with layouts )

Solution : stay float Add... To the label style control  display:inline; Convert it to inline properties

remarks : The one we use most often is div+CSS The layout is , and div It's a typical block attribute tag , In horizontal layout, we usually use div float Realized , Horizontal spacing setting if used margin Realization , This is an inevitable compatibility issue .

Browser compatibility issue 3 : Set smaller height label ( Generally less than 10px), stay IE6,IE7, The height is higher than the set height

Symptoms of the problem :IE6、7 And the height of this tag is not controlled in the roaming , Exceed the height set by yourself

Frequency :60%

Solution : Set up labels that are over height overflow:hidden; Or set the row height line-height  Less than the height you set .

remarks : This situation usually occurs in the label where we set a small rounded background . The reason for this problem is IE8 Previous browsers have given the label a minimum default line height .

Even if your tag is empty , The height of this tag will still reach the default row height .

Browser compatibility problem 4 : In line property labels , Set up display:block After using float Layout , There's another wild one margin The situation of ,IE6 spacing bug

Symptoms of the problem :IE6 The spacing ratio in is greater than the set spacing

Chance :20%

Solution : stay display:block; Add later display:inline;display:table;

remarks : In line property labels , To set the width and height , We need to set display:block;( except input The label is special ).

In use float Layout and have horizontal margin after , stay IE6 Next , He's got block attributes float The back landscape margin Of bug.

But because it's an in-line property tag , So we add display:inline Words , Its height and width cannot be set . At this time, we need to be in display:inline Add later display:talbe.

Browser compatibility 5 : There is a gap between the pictures by default

Symptoms of the problem : How many? img When the labels are put together , Some browsers have default spacing , Adding the wildcards mentioned in question 1 doesn't work .

Chance :20%

Solution : Use float The attribute is img Layout

remarks : because img Tags are inline property tags , So as long as it doesn't exceed the width of the container ,img The labels are all in one line , But some browsers img There will be a gap between the labels .

Remove this gap and use float It's the right way .( One of my students uses negative margin, Although it can solve , But negative margin It is a usage that easily causes browser compatibility problems , So I forbid them to use it )

Browser compatibility issue 6 : Label minimum height setting min-height Are not compatible

Symptoms of the problem : because min-height It's an incompatible one in itself CSS attribute , So set min-height Can't be well compatible with various browsers

Chance :5%

Solution : If we want to set the minimum height of a label 200px, The settings that need to be made are :{min-height:200px; height:auto !important; height:200px; overflow:visible;}

remarks : stay B/S When the front end of the system is on , There are many cases where we have this need . When the content is less than a value ( Such as 300px) when .

The height of the container is 300px; When the content height is greater than this value , The container is held high , Instead of scrollbars . At this time, we will face this compatibility problem .

Browser compatibility 7 : Transparency compatibility CSS Set up

The way to make a compatible page is : Write a little bit of code ( A line or piece of layout ) We all have to see if it's compatible in different browsers , Of course, to a certain degree of proficiency is not so troublesome .

It is recommended that novices who often encounter compatibility problems use . A lot of compatibility problems are caused by different resolution of default attributes of tags by browsers , With a little setup, we can easily solve these compatibility problems .

If we're familiar with the default properties of tags , You can understand why compatibility problems arise and how to solve them .

/* CSS hack*/  I seldom use hacker Of , Maybe it's a personal habit , I don't like to write code IE Are not compatible , And then use hack To solve .

however hacker It's still very easy to use . Use hacker I can divide browsers into 3 class :IE6 ;IE7 And travel ; other (IE8 chrome ff safari opera etc. )

IE6 cognitive hacker  It's underline _  And asterisk  *

IE7  Travel to know hacker It's an asterisk  *

Like this one CSS Set up :

height:300px;*height:200px;_height:100px; IE6 The browser is reading height:300px I think it's high time 300px;

Read on , He knows *heihgt,  So when IE6 Read *height:200px Will override the conflicting settings of the previous one , Think of the height as 200px.

Read on ,IE6 I know _height, So he'll cover it again 200px High settings , Set the height to 100px;

IE7 And travel is the same from height 300px Read on .

When they read *height200px And then it stopped , Because they don't know each other _height. So they're going to parse the height as 200px, The rest of the browsers only know the first height:300px; So they will parse the height as 300px.

Because the latter one will override the former one with the same priority and want to conflict , So the order of writing is very important .

How to let Chrome Support less than 12px Words of ?

answer :

htmlbody {-webkit-text-size-adjust: none;}

New version of the chrome It has been cancelled ;

CSS3 There's a new attribute transform, And that's what we're using transform:scale()

p{font-size:10px;-webkit-transform:scale(0.8);}

however , If , This attribute will take the entire p The properties of all scaling . What if I have a background ? I have a border ? Will be reduced !

So we changed the structure to

<p><span> I am a smaller than 12PX The font of </span></p>

The code is as follows

body,pmargin:0padding:0}
p{font-size:10px;}
span{-webkit-transform:scale(0.8); display:inline-block}

Definition  display:inline-block instead of  display:block; Will find .

There will be a certain margin . Looks like margin perhaps padding The distance between .

That's the problem with scaling . The original position is still occupied 12px Font size .

therefore , It should be modified accordingly margin 了 . Defined as negative .

There's also a way to share it online ;


html {font-size625%;}
body {font-size0.16rem;}

 

JavaScript Interview questions

JavaScript There are several types of data in ?

answer : Data types can be divided into Basic data type and Reference data type

Basic data type :StringNumberBoolean 、NullUndefinedSymbolBigInt ;

Reference data type :Object;

Some kids like to put Reference data type This one is divided into  Object  and  Funtion, That's ok ,( Mainly  typeof It can detect function, And that is Function This class is special )

among  SymbolBigInt  Is a new data type

JavaScript [] and {} What does it mean ?

answer :[] Represents an array ,

{} Representing objects ,

this 2 All of these statements are literal .

In addition to the literal way, you can also use new Array And new Object To instantiate .

JavaScript What is a global variable ? What is a local variable ? How is it defined ?

answer : A global variable is a variable defined outside a function , stay JS Global variables in window object , Its scope is the entire source program , All global variables are stored in static storage , Allocate storage to global variables at the beginning of program execution , The program is released after it runs .

Local variables are relative to global variables , Variables that can be accessed in a particular procedure or function , The scope is smaller , When the function is finished, the local variable is released .

stay JavaScript There is no explicit concept of local variables in , It is relative to other programming languages to describe .

Reference resources 《JavaScript Advanced programming 》 in , Variables are divided into global variables and function variables .

What is reserved word ? What should we pay attention to when defining variables ?

Reserved word is JavaScript Defined words in , Due to the consideration of scalability , Some reserved words may not be used in the current grammar , This is the difference between reserved words and keywords .

Such as class、abstract Is a reserved word . When you define variables, you should avoid using the same names as reserved words ;

say html Code ,css Code and js Code annotation method ?

answer :HTML Annotation syntax

<!-- Content of notes -->

css Annotation syntax

/*  The comment  */

javaScript notes

// The comment 
/* The comment */

Write one from 0 To 59 A timer that cycles in turn ?

answer :

var flag = 0;
function timer () {
  flag++;
  if (flag > 59) {
    flag = 0;
    return;
  }
  console.log(flag);
}
setInterval(timer, 1000);

JavaScript Event bubbling mechanism ?

answer : The mechanism of event propagation ( Whether it's DOM0 still DOM2, This mechanism is born with );

When an event action of the underlying element is triggered , The behavior of the corresponding level element will also trigger , All the way to our document;( Only the same event type will trigger )

The mechanism of upward propagation from the bottom level is called bubbling ;

DOM2 Level binding events , The third parameter writes false It stands for bubble stage execution , If it says true, Represents the execution in the capture phase ;

The same element can be processed either in the capture phase or in the bubbling phase ;

DOM0 The stage can only control the bubbling stage , and DOM2 Level can control the capture phase ;

Event delegation

utilize DOM The communication mechanism of ( Click on any element ,document Of click We have to start ), We give document Bind a click event , In an event, we just need to get the event source ; It's OK to do different events according to different event sources ( In this way, you don't have to give elements one by one to bind events );

When an event occurs in a child element , Wangwang can cause a chain reaction , Even on its ancestral element, this event happens , For example, you click div One , It's also equivalent to clicking on a body, It's the same as clicking html, It's the same as clicking document;

When understanding the spread of events, we should pay attention to two points ;

One is that the event itself is spreading , Instead of methods bound to events, they propagate ;

Second, not all events will spread , image onfocus,onblur Events don't spread ,onmouseenter and onmouseleave And events don't spread ;

We need to know what common default behavior of events is , And know the default behavior of the organization , Just add a sentence at the end of the method bound to the behavior event ,return false That's all right. ;

But it needs to be emphasized that , If your event binding is using addEventListener To achieve , Then the default behavior of the organization must use e.preventDefault=true;

Stop the event from bubbling

function (e) {
e.preventDefault();
}

Event delegation : Event delegation is the propagation mechanism of events , No matter which page element , its click Events will eventually reach us document On , such , Then you only need to document Upper processing click Events can be ;

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;
}

The key to event delegation is to understand the concept of event source ;

JavaScript What are the event compatibility issues ? How to solve ?

answer :1、 The event object itself , The standard browser automatically passes an argument to a method when time occurs , This argument is the time object ,IE Is a global window.event;( The solution is :e=e||window.event

2、 Event source :e.target,IE Next is e.srcElement;( The solution is  var target=e.target||e.srcElement;

3、DOM Second level event binding :ele.addEventListener,IE yes ele.attachEvent;

The solution is through

if(ele.addEventListener){

}else if(ele.attachEvent){
}

The corresponding removal method to solve the binding problem is removeEventListener and IE Of detachEvent;

4、 In the third point IE Of attachEvent The binding method ,

  1. The first point 、this Not the current element , It becomes window;
  2. Second point , The sequence of events is chaotic ;
    • stay IE678 in , If the binding method is less than 9 individual , The order of execution is reversed , If more than 9 individual , The execution is chaotic ;
  3. The third point , The same function can be bound to the same event repeatedly ;
    • We need to solve the problem that a function cannot be bound to the same event repeatedly , Low version IE This principle is not followed ; To ensure that a method can only be bound to an event the last time ;

5、 Stop the spread of events ;e.stopPropagation,IE yes e.cancelBubble=true This attribute ; This is not normally handled , With this property , You can also do observer mode ;

6、 Blocking default behavior :e.preventDefault() Method ,IE yes e.returnValue=false;

7、e.pageX,e.pageY; Mouse coordinates relative to the document IE These two properties are not supported ; But they all support clentX,clentY, This is the mouse coordinates relative to the browser . Can pass scrollTop+clientY To achieve ; Î


e.pageX=(document.documentElement.scrollLeft||document.body.scrollLeft)+ e.clientX;
e.pageY=(document.documentElement.scrollTop||document.body.scrollTop)+ e.clientY;

JavaScript DOM Create elements , Additive elements , Move elements , Replication node , Delete , Replacement elements , How to find nodes ?

answer : Create elements

document.createElement('tagName');

Additive elements

parent.appendChild(childNode);

notes : The method is called by the parent element

Move elements

because DOM Object is of reference type , So in operation appendChild and insertBefore When the method is used ,

If the control node is a node existing in the document , So we'll move this node to the target .

Replication node

oLi.cloneNode(true);

notes : Parameters true For deep cloning ( Deep copy ),false It means shallow cloning ( Shallow copy ), Deep copy is the number of replication nodes and the total number of nodes ; Shallow copy replication node itself . The node copy returned after replication belongs to the document , But no parent node is specified for it . therefore , The entire replica of the node becomes a ‘ 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>

Note the above code childNode Contains text nodes .

cloneNode() Method does not copy the addition DOM Node JS attribute , For example, event handler, etc . This method only copies features , Nothing else will be copied .

Delete node

parentNode.removeChild(childNode);

notes : The method is called by the parent element , The return value is the deleted node

Replacement elements

parentNode.replaceChild(newNode,oldNode);

notes :oldNode The node must be parentNode Child nodes of .

Insert elements

parentNode.insertBefore(newEle, oldNode);

notes : The method is called by the parent element

Summary of finding nodes

  • childNodes— Returns the node to child node list
  • firstChild— Returns the first child of the node ;
  • lastChild— Returns the last child of the node ;
  • nextSibling— Returns the peer node immediately after the node ;
  • nodeName— Returns the name of the node , According to its type ;
  • nodeType— Return the type of node ;
  • nodeValue— Sets or returns the value of the node , According to its type ;
  • ownerDocument— Returns the root element of the node (document object );
  • parentNode— Return the parent of the node ;
  • previousSibling— Returns the sibling node immediately before the node ;
  • text— Returns the text of the node and its descendants (IE alone possess );
  • xml— Returns the number of nodes and their descendants XML(IE alone possess );

Method of node object

  • appendChild()— Add a new child to the end of the node's child list ;
  • cloneNode()— Replication node ;
  • hasChildNodes()— Determine whether the current node has child nodes ;
  • insertBefore()— Inserts a new child node before the specified child node ;
  • normalize()— Merge adjacent Text Node and delete the empty Text node ;
  • removeChild()— Delete ( And back to ) The specified child of the current node ;
  • replaceChild()— Replace a child node with a new one ;

IE6 Unique method

  • selectNodes()— Use one XPath Expression Query select node ;
  • selectSingleNode()— Find and XPath Query a matching node ;
  • transformNode()— Use XSLT Convert a node into a string .transformNodeToObject()— Use XSLT Convert a node into a document .

Analysis of classical problems

Create a new node

  • createDocumentFragment() // Create a DOM fragment
  • createElement() // Create a specific element
  • createTextNode() // Create a text node

add to 、 remove 、 Replace 、 Insert

  • appendChild()
  • removeChild()
  • replaceChild()
  • insertBefore() // Insert a new child node before the existing one

lookup

  • getElementsByTagName() // By label name
  • getElementsByName() // By element Name The value of the property (IE Strong fault tolerance , You get an array , These include id be equal to name It's worth it )
  • getElementById() // Through elements Id, Uniqueness

Your DOM How to package ? How are the various libraries written ?(DOM library ,AJAX library , Animation library , Event library )?

answer : When scope sets scope ; Try not to return a reference data type in a child scope , Because of the value in the closure , Is the return value of another child closure , If the return value of a child closure is literal , Then the browser will be idle , Destroy the scope ; And if the return value is a reference data type value , So closures are not destroyed , In terms of performance optimization , Not good. !

Here is the idea of encapsulation ;

var Tool = function () {// Constructor Pattern ; You need it when you use it new once ;
    this.flag = "getElementsByClassName" in document;
    //getElementsByClassName  stay IE678 There is no such thing as . Use this to judge whether it is a low version IE browser ;
    // Every time you just need to judge this.flag Whether it exists or not ; If it exists, it's a standard browser , If it doesn't exist, it is IE;
};
Tool.prototype = {// The method is defined in Tool Of prototype Upper ;
    constructor: Tool,// rewrite prototype after ,prototype Of constructor It's not the original Tool 了 ; You need to manually force him to write Tool Up ;
    getIndex: function () {},// Simple notes ;
    toJSON:function(){},// Simple notes ;
    likeArray:function(){}// Simple notes ;
}

JavaScript Common methods of string ?

answer :

  • charAt Gets the character at the specified index location
  • charCodeAt Gets the character corresponding to the specified index position ASCII Code value
  • indeof/lasrIndexof Get a string in the first ( The last time ) Index of occurrence , If not, return to -1, We usually use this to detect whether a character is contained in a string ;
  • toUpperCase/tolowerCase Capitalize the letters in a string | A lowercase letter ;
  • split According to the specified separator , How to split a string into an array , And an array of join Corresponding ;
  • substr:substr(n,m) From the index n Began to intercept m Characters , Returns the truncated character to a new string ;
  • substring:substring(n,m) From the index n Start intercepting to index m It's about ( It doesn't contain m), Returns the character found as a new string ;
  • slice:slice(n,m) and substring It has the same usage and meaning , It's just slice You can support negative numbers as indexes , When a negative index appears , Use the length of the string + Negative index , for example :ary.slice(-6,-2), It's actually ary.slice(ary.length-6,ary.length-2)
  • The above three methods , If you only write one n, All are intercepted to the end of the string by default ;
  • Replace:replace(“ Old characters to replace ”,“ Replace with a new character ”) The method of character replacement in string , We can apply regularization to replace uniformly , In regular, we will explain in detail replace Powerful applications for ;
  • Match: Capture everything that matches the regular pattern ( Can't capture content in small groups )
  • trim: Remove the white space at the end of the string ( Are not compatible )

JavaScript Regular verification , When the form below is submitted , The input box cannot be empty , If there are spaces, you must remove them , It must be a legal mobile phone number ?

answer :

<form action="" id="form1" method="get">
   Phone number :<input type="text" value=" Enter the phone number " id="mobi" name=""/>
  <input type="submit" name=""/>
</form>
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;
  }
}

Explain it. JavaScript The same origin strategy ?

answer : Concept : Homology policy is client script ( In especial Javascript) An important security metric for .

It first came from Netscape Navigator2.0, Its purpose is to Prevent a document or script from loading from multiple sources .

The homology strategy here refers to : agreement , domain name , port identical ,

Homology policy is a security protocol : A script can only read the properties of windows and documents from the same source .

sketch JavaScript AJAX Principle ?

answer :ajax It's a collection of many technologies . These include

Browser's xmlHTTPRequest object , He's responsible for opening another connection for you , Can deliver information .

javascript: He's responsible for invoking XMLHTTPRequest Object to interact with the background .

xml Is a data format , The format used by the server to reply to pass information . except xml Outside , You can also use any text format , Include text,html,json etc. .

ajax It's not a new technology , It's a combination of several original technologies . It's a combination of the following technologies .

  1. Use CSS and XHTML To express .

  2. Use DOM Model to interact and dynamically display .

  3. Use XMLHttpRequest To communicate asynchronously with the server .

  4. Use javascript To bind and call .

In the above technologies , except XmlHttpRequest Beyond the object , All other technologies are based on web Standard and has been widely used ,XMLHttpRequest Although it has not yet been W3C Adopted , But it's already a standard of fact , Because it's supported by almost all the mainstream browsers right now .

XMLHttpRequest yes ajax The core mechanism of , It's in IE5 First introduced in , It's a technology that supports asynchronous requests . To put it simply , That is to say javascript It can make requests to the server and process the response in time , Without blocking users . Achieve no refresh effect .

So let's start with XMLHttpRequest Speak up , Let's see how it works .

XMLHttpRequest Properties of

Its properties are :

  • onreadystatechange The event handler for the event triggered by each state change .
  • responseText The string form of data returned from the server process .
  • responseXML Returned from the server process DOM Compatible document data objects .
  • status The numeric code returned from the server , For example, the common 404( Not found ) and 200( It's ready )
  • status Text String information accompanying the status code
  • readyState Object state value
    • 0 ( uninitialized ) Object created , But not yet initialized ( Not yet invoked open Method )
    • 1 ( initialization ) Object created , Not yet invoked send Method
    • 2 ( send data ) send Method called , But the current state and http Head unknown
    • 3 ( In data transmission ) Some data has been received , Because of the response and http The head is incomplete , At this time through responseBody and responseText There will be errors in getting some data ,
    • 4 ( complete ) Data received , This can be done by responseXml and responseText Get complete response data

however , Due to the differences between browsers , So create a XMLHttpRequest Objects may need different methods .

This difference is mainly reflected in IE And other browsers . Here's a more standard creation XMLHttpRequest Object method .


function CreateXmlHttp () {
// Not IE Browser creation XmlHttpRequest object 
if (window.XmlHttpRequest) {
xmlhttp = new XmlHttpRequest();
}
//IE Browser creation 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(" establish xmlhttp Object 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();
}

As shown above , Function first checks XMLHttpRequest And make sure it's done (readyStatus=4), That is, the data has been sent .

Then ask for the status of the request according to the settings of the server , If everything is ready (status=200), Then perform the following operations .

about XmlHttpRequest Two approaches ,open and send, among open The method specifies :

  • a、 The type of data submitted to the server , namely post still get.

  • b、 Requested url Address and passed parameters .

  • c、 transport ,false For synchronization ,true For asynchronous . The default is true. If it is asynchronous communication mode (true), The client doesn't wait for a response from the server ; If it's synchronous (false), The client has to wait for the server to return the message before performing other operations . We need to specify the synchronization mode according to the actual needs , In some pages , Multiple requests may be made , Even organized, planned, formed, large-scale, high-intensity request, The latter one will cover the former one , At this time, of course, you have to specify the synchronization mode .

Send Method is used to send the request

got it XMLHttpRequest workflow , We can see that ,XMLHttpRequest It's completely used to make a request to the server , Its role is also limited to this , But its role is the whole thing ajax The key to realization , because ajax It's just two processes , Making and responding to requests .

And it's completely a client technology . and XMLHttpRequest It is to deal with the problem of communication between the server and the client, so it is so important .

Now? , We are right. ajax Maybe we can understand the principle of . We can think of the server as a data interface , It returns a plain text stream , Of course , This text stream can be XML Format , It can be Html, It can be Javascript Code , It can be just a string .

Now ,XMLHttpRequest Request this page from the server , The server writes the results of the text to the page , This is the same as ordinary web The development process is the same , The difference is , After the client gets the result asynchronously , Not directly on the page , It's the first thing javascript To deal with it , Then it is displayed on the page . As for a lot of popular now ajax Control , such as magicajax etc. , Can return DataSet And other data types , It just encapsulates the result of this process , In essence, there is no big difference between them .

HTTP What are the status codes ? What do they mean ?

answer :

  • 100-199 Used to specify some actions that the client should take .
  • 200-299 Used to indicate that the request was successful .
  • 300-399 Used for files that have been moved and are often included in the location header information to specify new address information .
  • 400-499 Used to indicate client errors .400 1、 Semantically incorrect , The current request cannot be understood by the server .401 Current request requires user authentication 403 The server has understood the request , But refuse to execute it .
  • 500-599 Used to support server errors . 503 – Service not available ;

frequently-used

  • 100 Continue continue , Generally in the sending post When asked , Has been sent. http header After that, the server will return this information , confirm , Then send the specific parameter information
  • 200 OK Normal return information
  • 201 Created The request succeeded and the server created a new resource
  • 202 Accepted Request accepted by server , But not yet processed
  • 301 Moved Permanently The requested page has been permanently moved to a new location .
  • 302 Found Temporary redirections .
  • 303 See Other Temporary redirections , And always use GET Request new URI.
  • 304 Not Modified Since last request , The requested page has not been modified .
  • 400 Bad Request The server cannot understand the format of the request , Clients should not try to make requests again with the same content .
  • 401 Unauthorized Request not authorized .
  • 403 Forbidden Blocking access .
  • 404 Not Found Can't find how URI Matching resources .
  • 500 Internal Server Error The most common server-side errors .
  • 503 Service Unavailable The server is temporarily unable to process the request ( Possible overload or maintenance ).

A page input URL To the page loading display complete , What happened in the middle ?

answer :

  1. Type in the browser address bar ⼊URL
  2. Browser view cache , If the request resource is in the cache and fresh , Jump to transcoding step

    1. If the resource is not cached , Make a new request
    2. If cached , Check if ⾜ It's fresh enough ,⾜ Fresh enough to provide directly to the client , Otherwise, it will enter the ⾏ Examination Prove .
    3. There are usually two ways to test freshness HTTP Head in ⾏ control Expires and Cache-Control :
      • HTTP1.0 Provide Expires, The value is ⼀ An absolute time means that the cache is fresh ⽇ period
      • HTTP1.1 Added Cache-Control: max-age=, The value is the lowest value in seconds ⼤ Fresh time
  3. Browser parsing URL Get agreement , host , End ⼝,path

  4. Browser assembly ⼀ individual HTTP(GET) Ask for the newspaper ⽂

  5. Browser get host ip Address , The process is as follows :

    1. Browser cache
    2. Native cache
    3. hosts⽂ Pieces of
    4. Router cache
    5. ISP DNS cache
    6. DNS recursive query ( There may be load balancing that causes every time IP No ⼀ sample )
  6. open ⼀ individual socket And ⽬ mark IP Address , End ⼝ build ⽴TCP link , Three grip ⼿ as follows :

    1. The client sends ⼀ individual TCP Of SYN=1,Seq=X Package to server ⼝
    2. The server sends back SYN=1, ACK=X+1, Seq=Y Response package for
    3. The client sends ACK=Y+1, Seq=Z
  7. TCP Link building ⽴ Post send HTTP request

  8. The server accepts the request and parses , Forward the request to the server , Virtual host makes ⽤HTTP Host Head judgment, please The service procedure of the request

  9. Server check HTTP Whether the request header contains cache validation information, if the validation cache is fresh , return 304 And so on

  10. The handler reads the full request and prepares HTTP Respond to , It may be necessary to query the database

  11. The server will respond to the message ⽂ adopt TCP Connect send back to browser

  12. Browser reception HTTP Respond to , Then choose to turn off according to the situation TCP Connect or retain heavy ⽤, close TCP Connected four Second grip ⼿ as follows :

    1. Take the initiative ⽅ send out Fin=1, Ack=Z, Seq= X newspaper ⽂
    2. passive ⽅ send out ACK=X+1, Seq=Z newspaper ⽂
    3. passive ⽅ send out Fin=1, ACK=X, Seq=Y newspaper ⽂
    4. Take the initiative ⽅ send out ACK=Y, Seq=X newspaper ⽂
  13. Does the browser check the response status : Is it 1XX,3XX, 4XX, 5XX, These situations are related to 2XX Different

  14. If the resource can be cached , Into the ⾏ cache

  15. In response to ⾏ decode ( for example gzip Compress )

  16. Decide what to do based on resource type ( Assume the resource is HTML⽂ files )

  17. analysis HTML⽂ files , artifacts DOM Trees , Download resources , structure CSSOM Trees , Of board ⾏js Script , These operations are not strict The order of lattices , The following explains respectively

  18. structure DOM Trees :

    1. Tokenizing: according to HTML The specification parses a stream of characters into tags
    2. Lexing: Lexical analysis transforms tags into objects and defines properties and rules
    3. DOM construction: according to HTML Tag relationships make up objects DOM Trees
  19. Graph encountered during parsing ⽚、 Style sheets 、js⽂ Pieces of , Start download

  20. structure CSSOM Trees :

    1. Tokenizing: Conversion of character stream to label stream
    2. Node: Create nodes from tags
    3. CSSOM: Node creation CSSOM Trees
  21. according to DOM Trees and CSSOM Tree building rendering tree :

    1. from DOM The root node of the tree traverses all the possible ⻅ node , must not ⻅ Nodes include :1) script , meta This itself must not ⻅ The label of .2) By css Hidden node , Such as display: none
    2. For each ⼀ Personal ⻅ node , Find the right CSSOM The rules should not ⽤
    3. Publish the content and calculation style of visual nodes
  22. js The analysis is as follows :

    1. Browser creation Document Object and parse HTML, Will resolve to the elements and ⽂ This node is added to ⽂ In the file , this when document.readystate by loading
    2. HTML Has the parser encountered it async and defer Of script when , Add them to ⽂ In the file , Then hold ⾏⾏ Inside Or external scripts . These scripts are executed synchronously ⾏, And download and execute the script ⾏ The parser pauses . That way With ⽤document.write() hold ⽂ Ben chan ⼊ To lose ⼊ Streaming . Script and simple registration events are often defined The handler , They can traverse and manipulate script And before them ⽂ File content
    3. When the parser encounters the settings async Attribute script when , Start downloading scripts and continue parsing ⽂ files . The script will be in it Download as soon as possible ⾏, But the parser doesn't stop and wait for it to download . Asynchronous scripting is forbidden ⽌ send ⽤ document.write(), They can access ⾃⼰script And before ⽂ File element
    4. When ⽂ File complete parsing ,document.readState become interactive
    5. all defer The script will follow in ⽂ The order in which files appear ⾏, Delay scripts can access integrity ⽂ File tree , Forbid ⽌ send ⽤ document.write()
    6. The browser Document Trigger on object DOMContentLoaded event
    7. here ⽂ Complete parsing of file completed , The browser may still be waiting, as shown in the figure ⽚ And so on , Wait for these contents to be published ⼊ And all the asynchronous scripts are loaded ⼊ He Zhi ⾏,document.readState Turn into complete,window Trigger load event
  23. Show ⻚⾯(HTML The parsing process will gradually show ⻚⾯)

Asynchronous loading and delayed loading ?

answer :

  1. Asynchronous loading scheme : Dynamic insertion script label
  2. adopt ajax To get js Code , And then through eval perform
  3. script Add on label defer perhaps async attribute
  4. Create and insert iframe, Let it execute asynchronously js
  5. Delay loading : There are some js The code is not needed immediately when the page is initialized , And some of the later situations require .

Understanding of website reconstruction ? How to refactor a page ?

answer : How to refactor a page ?

To write CSS、 Make the page structure more reasonable , Enhance user experience , Achieve good page effect and improve performance .

Understanding of website reconstruction

Website reconstruction : Without changing the external behavior , Simplified structure 、 Add readability , And consistent behavior at the front of the site . That is to say, they are not changing UI Under the circumstances , Optimize the website , Keep consistent... While expanding UI.

For traditional websites, refactoring is usually

  • form (table) The layout is changed to DIV+CSS

  • Make the front end of the website compatible with modern browsers ( For substandard CSS、 If yes IE6 Effective )

  • For mobile platform optimization

  • Aim at SEO To optimize

  • Deep level website reconstruction should consider

  • Reduce code coupling

  • Keep the code elastic

  • Code in strict accordance with the specifications

  • Design extensible API

  • Replace the old frame 、 Language ( Such as VB)

  • Enhance the user experience

  • Generally speaking, speed optimization is also included in the reconstruction

  • Compress JS、CSS、image Other front-end resources ( It's usually done by the server )

  • Program performance optimization ( Such as data reading and writing )

  • use CDN To speed up resource loading

  • about JS DOM The optimization of the

  • HTTP The file cache of the server

JavaScript new What do operators do ?

answer :

  • Create an empty object , also this Variable references the object , It also inherits the prototype of the function
  • Properties and methods are added to this In the referenced object
  • The newly created object is created by this The referenced , And finally implicitly returns this

var obj = {};
obj.__proto__ = Base.prototype;
Base.call(obj);

 

JavaScript call and apply() Functions and differences of ?

answer : The core

Dynamically change the running environment of a method of a class , Change  this  keyword

  • call It is the transmission of parameters one by one
  • apply It is to pass in the parameter as a data , similar arguments;

call and apply The difference between

  • Function.prototype.call and Function.prototype.apply They do the same thing , The difference is only in the form of the incoming parameter .

  • When using call perhaps apply When , If the first parameter we pass in is null, In function body this Will refer to To the default host object , In the browser, it is window

  • Sometimes we use call perhaps apply The purpose of this is not to refer to set this Point to , It's something else , Like borrowing methods from other objects . So we can pass in null Instead of a specific object

call and apply Use of

  1. change this Point to
  2. Function.prototype.bind
  3. Borrow 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);
// use  add  To replace  sub,add.call(sub,3,1) == add(3,1) , So the result is : (4);

js The functions in are actually objects , The function name is right Function References to objects

JavaScript Talk about  this  Understanding of the object ?

answer :

  • this  Refers to the object that called the function
  • this  You can't know who it represents until it's running ;js Of this  The direction is uncertain ; It has nothing to do with definition , It's about execution ,
  • When it comes to execution , Who's in front of the dot ,this  Who is the ; Self executing function this  It stands for  window
  • When the timer is writing ,window Can be omitted ; When the timer is running , Inside this  Also represents  window ;
  • this  yes js One of the keywords of , As functions are used in different situations ,this  The value of will change .

JavaScript What is? window object ? What is? document object ? Talk about your understanding

answer :

  • document yes window An object property of .
  • window Object represents an open window in the browser .
  • If the document contains a framework (frame or iframe label ), The browser will be HTML The document creates a window object , And create an extra... For each frame window object .
  • All global functions and objects belong to Window Properties and methods of objects .
    • for example , Can only write document, Without writing window.document.
    • Again , You can use the method of the current window object as a function , If only write alert(), Without writing Window.alert().
  • document Yes Document Read only reference to object .

Javascript Several ways to create objects ?

answer :

  1. Factory mode
  2. Constructor Pattern
  3. Archetypal model
  4. Mix constructors and prototype patterns
  5. Dynamic prototype pattern
  6. Parasitic constructor mode
  7. Safe constructor mode

javascript To create an object, simply say , It's just using built-in objects or various custom objects . Of course, it can also be used JSON; But there are many ways of writing . It can also be mixed .

1、 The way in which objects are literally measured

person={
firstname:"zhu",
lastname:"anbang",
age:25,
eyecolor:"black"};

2、 use function To simulate a parameterless constructor

function Person(){}
var person=new Person();// Define a function.  If you use new" Instantiation ", The function Can be seen as a Class
person.name="zhu";
person.age="25";
person.work=function(){
alert(person.name+" hello...");
}
person.work();

3、 use function To simulate a parameter constructor to implement ( use this Keyword defines the context property of the construct )

function Pet(name,age,hobby){
this.name=name;//this Scope : The current object 
this.age=age;
this.hobby=hobby;
this.eat=function(){
alert(" My name is "+this.name+", I like "+this.hobby+", A programmer ");
}
}
var maidou =new Pet(" McDull ",25,"coding");// Instantiation 、 Create objects 
maidou.eat();// call eat Method 

4、 Create... In a factory way ( Built-in objects )

var wcDog =new Object();
wcDog.name=" Wangcai ";
wcDog.age=3;
wcDog.work=function(){
alert(" I am a "+wcDog.name+", Wang Wang Wang ......");
}
wcDog.work();

5、 Create... As a prototype

function Dog(){}
Dog.prototype.name=" Wangcai ";
Dog.prototype.eat=function(){
alert(this.name+" It's a foodie ");
}

var wangcai =new Dog();
wangcai.eat();

5、 Create... In a hybrid way


function Car(name,price){
this.name=name;
this.price=price;
}
Car.prototype.sell=function(){
alert(" I am a "+this.name+".  I'm selling "+this.price+" Ten thousand yuan ");
}
var camry =new Car(" camry ",27);
camry.sell();

JavaScript How to do modular development ?

answer : The core : Immediate execution function , Don't expose private members

var module1 = (function () {
var _count = 0;
var m1 = function () {
//...
};
var m2 = function () {
//..
};
return {
m1: m1,
m2: m2
};
})();

Find the maximum value in the array  var ary=[1,2,3,5,7,90,3,6];

answer :alert(Math.max.apply(null,a)).

Knowledge point : take a Pass as a parameter , The return value is the new array after sorting , The first parameter is zero null Because you don't need to borrow objects , 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
 Be careful :a Is passed in as an argument , Because the calling object can be ignored , So the first parameter is null,

Math.max.apply A new value is returned .

Another way is , Prioritize , And then the head and tail are what we want ;


ary.sort(function(a,b){return a-b})
console.log(ary[0]);
console.log(ary[ary.length-1]);

js Deep cloning of objects ?

answer :

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 properties to this object  
      buf[k] = clone(Obj[k]);
    }
    return buf;
  } else {
    return Obj;
  }
}

 

Network communication interview questions

HTTP Status code and its meaning ?

answer :

  • 1XX : Information status code
    • 100 Continue continue ,⼀ Sending post When asked , Has been sent. http header Then the server
    • This information will be returned , confirm , Then send the specific parameter information
  • 2XX : Success status code
    • 200 OK Normal return information
    • 201 Created The request succeeded and the server created a new resource
    • 202 Accepted Request accepted by server , But not yet processed
  • 3XX : Redirect
    • 301 Moved Permanently Requested ⽹⻚ Has been permanently moved to a new location .
    • 302 Found Temporary redirections .
    • 303 See Other Temporary redirections , And always make ⽤ GET Request new URI .
    • 304 Not Modified ⾃ Since the last request , Requested ⽹⻚ Not modified .
  • 4XX : Client error
    • 400 Bad Request The server ⽆ How to understand the format of request , The client should not try to make ⽤ The same inside
    • Let's make a request .
    • 401 Unauthorized Request not authorized .
    • 403 Forbidden Forbid ⽌ visit .
    • 404 Not Found Can't find how URI Matching resources .
  • 5XX: Server error
    • 500 Internal Server Error Most often ⻅ Server side error for .
    • 503 Service Unavailable Server side temporarily ⽆ Cannot process the request ( Possible overload or maintenance ).

HTTP Of ⼏ Kind of request ⽅ Law ⽤ Way ?

answer :

GET ⽅ Law

  • send out ⼀ Requests to get some from the server ⼀ resources

POST ⽅ Law

  • towards URL The specified resources submit data or attach new data

PUT ⽅ Law

  • Follow POST ⽅ The law is very similar to , I also want to submit data to the server . however , There are differences between them . PUT Specifies the location of the resource on the server ,⽽ POST No,

HEAD ⽅ Law

  • Only request ⻚⾯ Of ⾸ Ministry

DELETE ⽅ Law

  • Delete a resource on the server

OPTIONS ⽅ Law

  • it ⽤ Get at present URL the ⽀ Hold on to ⽅ Law . If the request succeeds , There will be ⼀ individual Allow The head of contains similar “GET,POST” Such information

TRACE ⽅ Law

  • TRACE ⽅ Dharma quilt ⽤ Yu excited ⼀ A remote , Should be ⽤ Request message loop of layer

CONNECT ⽅ Law

  • Convert the request connection to transparent TCP/IP passageway

Talk about it. WebSocket?

answer : because http There is ⼀ One obvious drawback ( Messages can only be pushed from the client to the server ,⽽ clothing Server can't push to client ), If the server has continuous changes , It's just Can make ⽤ polling ,⽽ Polling efficiency is too low , Not suitable for . therefore WebSocket To be invented

phase ⽐ And http It has the following points

  • ⽀ Two way communication , More real time ;
  • Can send ⽂ Ben , It's fine too ⼆ Base number ⽂ Pieces of ;
  • The protocol identifier is ws , After encryption is wss ;
  • Less control overhead . After the connection is created , ws client 、 Service end-to-end ⾏ Data exchange , The packet header controlled by the protocol is smaller than ⼩. Without the head , The service end to the client's header is 2~10 byte ( Depending on the packet ⻓ degree ), From client to server , Need to add extra 4 Mask of bytes .⽽ HTTP The protocol needs to carry a complete head every time it communicates ;
  • ⽀ Keep expanding .ws The protocol defines the extension ,⽤ User extensible protocol , Or realize ⾃ Defined ⼦ agreement .(⽐ Such as ⽀
  • a ⾃ Define compression algorithm, etc )
  • ⽆ Cross-domain problem .

Realization ⽐ Simpler , Server libraries such as socket.io 、 ws , It can help us a lot ⼊⻔.

⽽ The client only needs reference api It can be realized

ajax、axios、fetch difference ?

answer :jQuery ajax

$.ajax({
type: 'POST',
url: url,
data: data,
dataType: dataType,
success: function () {},
error: function () {}
});

Advantages and disadvantages :

  • It's about MVC Programming for , Not in line with the current front end MVVM The wave of
  • Based on the original ⽣ Of XHR Development , XHR The structure is not clear , Already there. fetch An alternative ⽅ case
  • JQuery The whole item ⽬ too ⼤, Simply make ⽤ ajax But it will lead to ⼊ Whole JQuery ⾮ Often unreasonable ( Take personalized packaging ⽅ case ⼜ Cannot enjoy 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);
});

Advantages and disadvantages :

  • Created from the browser XMLHttpRequest
  • from node.js issue http request
  • ⽀ a Promise API
  • Intercept requests and responses
  • Transform the request and response data
  • Cancel the request
  • ⾃ Dynamic conversion JSON data
  • client ⽀ Be on guard against ⽌ CSRF/XSRF

fetch

try {
let response = await fetch(url);
let data = response.json();
console.log(data);
} catch(e) {
console.log("Oops, error", e);
}

Advantages and disadvantages :

  • fetcht Only right ⽹ Please report an error , Yes 400 , 500 All as successful requests , Need to be packaged to handle
  • fetch Default will not bring cookie , Configuration items need to be added
  • fetch No ⽀ a abort , No ⽀ Hold time-out control , send ⽤ setTimeout And Promise.reject The implementation of the timeout control does not prevent ⽌ The request process continues in the background ⾏, It's a waste of quantity
  • fetch There is no way ⽣ Monitor the progress of the request ,⽽XHR Sure

Ajax Read a xml Document and parsing instance ?

answer :

var xhr = new XMLHttpRequest;//-> stay IE7 The following browsers are not compatible 
xhr=new ActiveXObject("Microsoft.XMLHTTP");
xhr=new ActiveXObject("Msxml2.XMLHTTP");
xhr=new ActiveXObject("Msxml3.XMLHTTP");
//-> Inert thought 
var getXHR = (function () {
  //-> Store the few acquisitions we need Ajax Object method 
  var ajaxAry = [
    function () {
      return new XMLHttpRequest;
    },
    function () {
      return new ActiveXObject("Microsoft.XMLHTTP");
    },
    function () {
      return new ActiveXObject("Msxml2.XMLHTTP");
    },
    function () {
      return new ActiveXObject("Msxml3.XMLHTTP");
    }
  ];
  //-> Circular array , Carry out the four methods in turn 
  var xhr = null;
  for (var i = 0; i < ajaxAry.length; i++) {
    //-> Standard browser :i=0, Get the first function function(){return new XMLHttpRequest;}(A1), No error was reported during the execution ,xhr It's the return value, and it's ours Ajax object , You can't go without reporting a mistake catch, perform getXHR = A1, This way, the outside of getXHR Rewrote , encounter break The loop ends 
    //->IE6 browser :i=0, Gets the first function execution ,IE6 I won't support it XMLHttpRequest, So there's an error , perform catch Medium continue Continue the next cycle ,i=1, Get the second function  function(){return new ActiveXObject("Microsoft.XMLHTTP");}(A2), There is no error in execution , So start implementing getXHR = A2, encounter break End the cycle , At this time, outside 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 much LOW Is that right , Can we have fun ~~");
  }
  return getXHR;
})();
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);

Avoid returning data that is garbled

-> The front page is UTF-8 code , If the data we requested from the server is not UTF-8 Coding format , In the content obtained , Chinese characters will be garbled

-> We need to use ”UTF-8 The ultimate principle ”: Front page 、JS、CSS、 Background code 、 database 、 The data transmitted by the request is uniformly encoded by one code UTF-8

->[RESPONSE] Content-Type:text/plain( Pure text )、application/json(JSON Format )… Format the content in the response body

front end : Set request header , Get response header

-> At the front JS We can use  xhr.setRequestHeader([name],[value])  Set request header information ;

have access to  xhr.getResponseHeader([name])/xhr.getAllResponseHeaders()  Get response header information ;

Server side : Get request header , Set the response header

-> stay NODE We can use  response.writeHead(200, {'content-type': 'application/json'}); Set response header information

-> stay NODE We can use request This object gets the request information ( Start line 、 The first one 、 The main body ) Can be obtained from

Multiplexing and demultiplexing ?

answer : The task of delivering the data in the transport layer message segment to the correct socket is called demultiplexing .

Collect data from different sockets on the source host , After the package header information is generated into a message segment , Passing a message segment to the network layer , This process is called multiplexing .

Connectionless multiplexing and demultiplexing refer to UDP Socket allocation process , One UDP The socket is identified by a binary , This binary contains one A destination address and a destination port number . So it's not the same source address and port number UDP After the message segment arrives at the host computer , If they have the same destination address and destination slogan , Then different segments will be passed on to the same UDP Socket .

Connection oriented multiplexing and demultiplexing refer to TCP Socket allocation process , One TCP The socket is identified by a quad , This quad contains Source IP Address 、 Source port number 、 Destination address and destination port number . therefore , One TCP When a segment arrives at a host from the network , This host uses all 4 individual Value to direct the segment to the corresponding socket .

UDP agreement ?

answer :UDP It's a connectionless , Unreliable transport layer protocol . It only provides the minimum functions that the transport layer needs to achieve , Besides reuse / Decomposition function and a small amount of difference In addition to error detection , It has little to do with IP Add something else .UDP The protocol is suitable for real-time applications .

characteristic :

  1. Use UDP when , Before sending a segment , There is no handshake between the two sides of the communication , therefore UDP It's called a connectionless transport layer protocol . Because there was no handshake The process , be relative to TCP Come on , There is no connection delay . Because there's no connection , So there's no need to save the state of the connection in the end system .

  2. UDP Provide best effort delivery services , in other words UDP The protocol does not guarantee reliable delivery of data .

  3. UDP There is no congestion control and flow control mechanism , therefore UDP There is no limit to the sending rate of message segments .

  4. Because a UDP The socket only uses the destination address and destination port to identify , therefore UDP Can support one-on-one 、 One to many 、 One to many interactions signal communication .

  5. UDP Small head , Only 8 Bytes .

UDP Segment structure

UDP Message segment consists of header and application data . The header of a message segment contains four fields , The source port number 、 Destination port number 、 Length and inspection and , The length of each field The degree is two bytes . The length field refers to the length of the whole message segment , Contains the size of the header and application data . The check sum is UDP Provides an error checking mechanism . Although error checking mechanism is provided , however UDP There's nothing to do with the recovery of errors .

UDP  Segment structure

TCP agreement ?

answer :TCP The protocol is connection oriented , Transport layer protocol providing reliable data transmission service .

characteristic :

  1. TCP The protocol is connection oriented , Before communication between two parties , It takes three handshakes to establish a connection . It needs to maintain the state information of the connection between the two sides in the end system .

  2. TCP The agreement passed the serial number 、 Confirmation no. 、 Timed retransmission 、 Testing and other mechanisms , To provide reliable data transmission services .

  3. TCP The agreement provides a point-to-point service , That is, it is a connection between a single sender and a single receiver .

  4. TCP The protocol provides full duplex service , In other words, both sides of the connection can send and receive data to each other .

  5. TCP Congestion control mechanism is provided , The rate of sending data will be controlled when the network is congested , It helps to reduce packet loss and reduce congestion in the network .

  6. TCP The flow control mechanism is provided , Ensure that both sides of the communication send and receive the same rate . If the receiver has a very small cache to receive , The sender will reduce the transmission cost rate , Avoid packet loss due to cache filling .

TCP Segment structure

TCP A message segment consists of a header and data , The first part of it is usually 20 Bytes .

Source port and destination port numbers are used for multiplexing and decomposition of message segments .

32 The number of bits and 32 The confirmation number of the bit , Using and implementing reliable data transport services .

16 The receiving window field of bit is used to realize flow control , This field represents the number of bytes the receiver is willing to receive .

4 The first length field of a bit , This field indicates that 32 Bits of words are units of TCP The length of the head .

6 Bit flag field ,ACK Field is used to indicate that the value of the confirmation number is valid ,RST、SYN and FIN Bits are used to establish and dismantle connections . Set up PSH word Segment indicates that the receiver should immediately hand over the data to the upper layer ,URG Field is used to indicate that there is urgent data in the message segment .

Checksums provide error detection of data .

TCP  Segment structure

TCP Three handshakes

The first handshake , The client sends a... To the server SYN Connection request segment , In the header of a message segment SYN The location of the sign is 1, The ordinal field is an optional random number . It represents the initial serial number of the client data .

The second handshake , The server receives a message from the client SYN After connecting request message segment , The server will first assign TCP Caching and variables , And then to The client sends SYN ACK Message segment , In the header of a message segment SYN and ACK The flag bits are set to 1, On behalf of this is a right choice SYN Confirmation of connection request , At the same time, the serial number field is an optional random number generated by the server , It represents the initial sequence number of the server-side data . The confirmation number field is the serial number sent by the client plus One .

The third handshake , After the client receives the positive response from the server , It will also be for this time TCP Connection allocation cache and variables , At the same time, send a pair of services to the server Acknowledgement of message segment at the terminal . The third handshake can carry data in the message segment .

in my opinion ,TCP The process of establishing the connection by three handshakes is the process of confirming the initial serial number of each other , Tell them , What kind of serial number message segment can be correctly received . The function of the third handshake is to confirm the initial serial number of the server by the client . If only two handshakes are used , Then the server has no way to know if its serial number is It has been confirmed that . At the same time, this is also to prevent invalid request segments from being received by the server , And errors occur .

TCP The process of waving four times

because TCP Connection is full duplex , That is to say, both sides of communication can send and receive messages to each other , So disconnection requires confirmation from both parties .

First wave , The client thinks that there is no data to send to the server , It sends a FIN Message segment , Apply to disconnect the client from the server Connect . After sending, the client enters FIN_WAIT_1 state .

Second wave , After the server receives the client's request to release the connection , Send an acknowledgement message segment to the client , Indicates that a client release connection has been received request , In the future, we will not receive the data sent by the client . But because the connection is full duplex , So at this time , The server can also send data to the client . service The end of the machine enters CLOSE_WAIT state . After the client receives the confirmation , Get into FIN_WAIT_2 state .

Third wave , After the server sends all the data , Send to the client FIN Message segment , Request to disconnect the server from the client . Send and enter LAS T_ACK state .

Fourth wave , The client received FIN After the request , Send a confirmation response to the server , And enter TIME_WAIT Stage . This phase will last for a while , This time is the maximum lifetime of a message segment in the network , If the server does not resend the request within that time , Client access CLOSED The state of . If you receive The resend request of the server will resend the confirmation message segment . After receiving the confirmation message segment from the client, the server enters CLOSED state , In this way, the full duplex connection is The release of the .

TCP The reason to wave four times is because TCP The connection is full duplex , So we need to release the connection to each other , Single party connection release , Only for The table can no longer send data to the other party , The connection is in a semi released state .

One last wave , The reason why the client will wait for a period of time to shut down , It is to prevent the loss or error of the acknowledgement message segment sent to the server , This causes the server to The terminal does not close properly .

State transformation diagram

 Client state diagram

 Server state diagram

ARQ agreement

ARQ Protocol refers to automatic retransmission request , It guarantees reliable delivery of data through timeout and retransmission , It is TCP Protocol to achieve reliable data transmission is a very important Mechanism .

It's divided into stop waiting ARQ Agreement and continuity ARQ agreement .

One 、 Stop waiting ARQ agreement

Stop waiting ARQ The basic principle of the protocol is , For the sender, each packet sent by the sender , Just set a timer for this group . When sending a packet confirmation The answer goes back to , Then clear the timer , Send next packet . If you do not receive a positive response from the sent packet within the specified time , Then resend the previous packet .

For the recipient , One group is received at a time , The answer to this group is yes , When redundant packets are received , Just throw it away , And returns a pair of redundancy Group confirmation . When you receive a packet corruption , Direct discarding .

Use stop waiting ARQ The disadvantage of the protocol is that each time a packet is sent, it must wait until the packet is confirmed before sending the next packet , This will result in low channel utilization .

Two 、 continuity ARQ agreement

continuity ARQ The agreement is to solve the problem of stop waiting ARQ The problem of low channel utilization rate of the protocol . It sends a group of packets in succession , Then wait for the Confirm the answer , How to deal with the possible error recovery in the packet , Generally, sliding window protocol and selective retransmission protocol can be used .

  1. Sliding window protocol

Using sliding window protocol , A send window is maintained at the sender , The previous packets in the send window are those that have been sent and confirmed , Send window contains sent Packets sent but not confirmed and packets allowed to be sent but not yet sent , The packets after the sending window are not allowed to be sent in the cache . When the sender sends a minute to the receiver Group time , All packets in the window are sent in turn , And set a timer , This timer can be understood as the earliest packet sent but not received an acknowledgement . If you are setting The timer receives the confirmation answer of a certain group in time , Then slide the window , Move the head of the window to the next position after the confirmation group , If it has not been sent at this time There are confirmed groups , Reset the timer , If not, turn off the timer . If the timer times out , All that have been received have not been sent again Group .

The receiver uses a cumulative acknowledgement mechanism , For all packets arriving in order , The receiver returns a grouped positive answer . If you receive an out of order packet , that The receiver will discard it directly , And return a positive answer to the nearest group that arrived in order . The use of cumulative acknowledgement ensures that the previous groups of the confirmation number have arrived in order , So the sending window can be moved to the back of the confirmed packet .

The disadvantage of the sliding window protocol is that it uses a cumulative acknowledgement mechanism , If it appears, only the first group in the window is lost , And the latter groups all arrive in order Words , So the sliding window protocol will resend all the packets , As a result, a large number of unnecessary packets are discarded and retransmitted .

  1. Choose retransmission protocol

Because the sliding window uses cumulative confirmation , So it will cause a lot of unnecessary packet retransmission . Using selective retransmission protocol can solve this problem .

Selecting the retransmission protocol maintains a sending window at the sender . In the send window are the packets that have been sent and confirmed , The window contains packets that have been sent but not confirmed , Confirmed out of order grouping , And packets that are allowed to be sent but not yet sent , After the sending window are the packets that are not allowed to be sent in the cache . Choose retransmission protocol and slide window protocol The biggest difference is that , When the sender sends a packet , Create a timer for each group . When the sender receives an acknowledgement from a packet , Cancel the Timer , After accepting the group, we can judge whether there is any difference between the two groups , The existence of the first consecutive window is confirmed by the first group , If so, move the position of the window backward , If not, the score will be reduced The group is identified as a received out of order packet . When a packet timer arrives , The packet is retransmitted .

At the receiver , It will confirm that each packet received correctly , Whether the grouping is in order or out of order , Out of order packets will be cached , Until all the disorder After all the groups arrive to form an ordered sequence , And then we'll send this segment to the upper layer . For packets that cannot be correctly received , The receiver directly ignores the packet .

TCP Reliable transportation mechanism

TCP Our reliable transport mechanism is based on continuous ARQ Protocol and sliding window protocol .

TCP The protocol maintains a sending window at the sender , The message segment before the sending window is the one that has been sent and confirmed , The send window contains the sent but Unacknowledged message segments and messages allowed to be sent but not yet sent , The message segment after the sending window is one that is not allowed to be sent in the cache . When the sender sends to the receiver When delivering papers , All message segments in the window will be sent in turn , And set a timer , This timer can be understood as the earliest sent but not received message segment . If the confirmation answer of a message segment is received within the timer time , Then slide the window , Slide the head of the window back to the next position in the acknowledgement segment , At this time, it's like If there are any message segments that have been sent but not confirmed , Reset the timer , If not, turn off the timer . If the timer times out , Then resend all the messages that have been sent But the confirmed message segment has not been received , And set the timeout interval to twice the previous one . When the sender receives three redundant acknowledgements from the receiver , It's an indication , It indicates that the message segment after the message segment is likely to be lost , Then the sender will enable the fast retransmission mechanism , Before the end of the current timer , Send all sent Send but confirm message segment .

The receiver uses a cumulative acknowledgement mechanism , For all segments arriving in sequence , The receiver returns a positive answer to a message segment . If an out of order message is received paragraph , Then the receiver will discard it directly , A message that answers the most recent message arrives in sequence . The cumulative acknowledgement ensures that the message segments before the returned acknowledgement number are It has arrived in order , So the sending window can be moved to the back of the confirmed message segment .

The size of the send window varies , It is determined by the remaining size of the receiving window and the degree of congestion in the network ,TCP It is to control the message by controlling the length of the sending window The transmission rate of segments .

however TCP The protocol is not exactly the same as the sliding window protocol , Because a lot of TCP The implementation will cache out of order segments , And retransmission occurs , It's just heavy Send a message segment , therefore TCP The reliable transmission mechanism of the protocol is more like a mixture of window sliding protocol and selective retransmission protocol .

TCP Flow control mechanism of

TCP Provides flow control services , The main purpose of this service is to control the sending rate of the sender , To ensure that the receiving party can receive . Because once the transmission rate is high At the rate the receiver can receive , It will cause the loss of message segment . The receiver mainly tells the sender the size of receiving through the receiving window , The sender is based on The size of the receiving window to adjust the size of the sending window , In order to control the sending rate .

TCP Congestion control mechanism of

TCP Congestion control is mainly based on the network congestion to control the sender data transmission rate , If the network is congested , The sender reduces the transmission cost rate , On the one hand, it is to avoid increasing the degree of congestion in the network , On the other hand, it is also to avoid packet segment loss caused by network congestion .

TCP Four mechanisms are used in the congestion control , Slow start 、 Congestion avoidance 、 Fast retransmission and fast recovery .

The basic idea of slow start is , Because when the sender starts sending data , I don't know the degree of congestion in the network , So send it at a lower rate first , Testing , One confirmation message is received at a time , Add one to the length of the launch window , So each of them RTT After time , The length of the send window will double . When the size of the send window reaches When it reaches a threshold, it enters the congestion avoidance algorithm .

Congestion avoidance algorithm is to avoid possible congestion , The size of the sending window is changed from one to the other RTT Double , Become every one RTT , Just add one to the length . In this way, the growth rate of the window will increase exponentially , Change to additive linear growth .

Fast retransmission refers to , When the sender receives three redundant acknowledgements , because TCP It's a cumulative confirmation mechanism , So it's very likely that a message segment The loss of , Therefore, an immediate retransmission mechanism is adopted , Before the end of the timer, send all the message segments that have been sent but have not received the confirmation response .

Fast recovery is the subsequent processing of fast retransmission , Because there may be congestion in the network , So the threshold value of slow start will be reduced to half of the original value , And then it will embrace The value of the plug window is set to the halved threshold value , Then start to implement congestion avoidance algorithm , It makes the congestion window increase slowly . To put it simply, it means , Multiplicative subtraction , Additive increase .

TCP The main basis of network congestion is the retransmission times of the message segment , It depends on the degree of congestion in the network , By adjusting the threshold of slow start , Then use the top four alternately To achieve the goal of congestion control .

Post and Get The difference between ?

answer :Post and Get yes HTTP Two ways to request .

  • (1) From the perspective of application scenarios ,GET A request is an idempotent request , commonly Get Requests are used in scenarios where there is no impact on server resources , For example, request a web page . and Post Not an idempotent request , It is generally used for scenarios that have an impact on server resources . For example, operations like registering users .

  • (2) Because of different application scenarios , So the browser will generally Get Request cache , But rarely to Post Request cache .

  • (3) In terms of the format of the message sent ,Get The entity part of the requested message is empty ,Post The entity part of the request message is generally the data sent to the server .

  • (4) however Get The request can also put the parameters of the request into url Send to server in ,

    • This approach is relative to Post The request for , One aspect is that it's not very safe , Because of the request url Will be kept in history . And the browser is able to url There is a length limit , So it will affect get The length of the request to send data . This restriction is set by the browser , Not at all RFC Stipulated . And that is post More data types are supported by parameter passing of .

DNS Why use UDP Protocol as transport layer protocol ?

answer :DNS Use UDP The main reason why the protocol is used as a transport layer protocol is to avoid the use of TCP Connection delay caused by protocol .

Because in order to get a domain name IP Address , It often queries multiple domain name servers , If you use TCP agreement , Then there will be a connection delay for each request , In this way DNS The service is getting slow , Because most of the address inquiry requests , It's all sent out when the browser requests the page , This will cause the web page to wait too long .

Use UDP Act of agreement DNS There will be a problem with the agreement , For historical reasons , Minimum physical link MTU = 576, So in order to limit the length of message to no more than 576,UDP The length of the segment is limited to 512 Within bytes , So once DNS Query or response message of , More than the 512 byte , Then based on UDP Of DNS The agreement will be truncated to 512 byte , So it's possible that users will get DNS The response is incomplete . here DNS Once the length of the message exceeds the limit , It's not like TCP The protocol is then split into multiple segments for transmission , because UDP The protocol does not maintain connection state , So we have no way to determine which segments belong to the same data ,UDP It only intercepts the redundant data .

To solve this problem , We can use TCP Protocol request message .

DNS Another problem is security , It's that we can't be sure of the response we get , It must be a safe response , Because responses can be forged by others , So now there is DNS over HTTPS To solve this problem .

Talk about CDN service ?

answer :CDN It's a content distribution network , By caching the source site resources , Using itself, multiple stations are located in different regions 、 Servers from different operators , Providing users with access to nearby information function . in other words , The user's request is not sent directly to the source website , But to CDN The server , from CND The server locates the request to the nearest containing the resource On the server . This is conducive to improving the speed of website access , At the same time, it also reduces the access pressure of the source server .

What are forward and reverse agents ?

answer : We often say agency, that is, forward agency , The process of forward agency , It hides the real request client , The server does not know who the real client is , Requested by the client Services are replaced by proxy servers to request .

The reverse proxy hides the real server , When we ask for a website , There may be thousands of servers behind us , But which one is it , We don't know Avenue , I don't need to know , We just need to know who the reverse proxy server is , The reverse proxy server will help us forward the request to the real server . reverse Agents are generally used for load balancing .

There are two ways to realize load balancing ?

answer : One way is to use reverse proxy , The user's requests are sent to the reverse proxy service , The reverse proxy server then forwards the request to the real server , In this way Load balancing of existing cluster .

The other is DNS The way ,DNS Can be used for load balancing on redundant servers . Because now the general large-scale website uses multiple servers to provide services , So one Domain names may correspond to multiple server addresses . When the user requests the domain name of the website ,DNS The server returns the server corresponding to the domain name IP A collection of addresses , But in In every answer , It's going to cycle these IP The order of addresses , Users usually choose the top address to send the request . In this way, users' requests are evenly distributed to different services On the server , This is to achieve load balancing . One drawback of this approach is , because DNS There is a cache in the server , So it's possible that after a server fails , Domain name solution The analysis still returns to that one IP Address , It will cause access problems .

Realization of instant messaging , Short polling 、 Long polling 、SSE and WebSocket Distinction between ?

answer : The purpose of short polling and long polling is to realize an instant communication between client and server .

The basic idea of short polling is that the browser sends to the browser at regular intervals http request , After the server receives the request , Whether there is data update or not , It's all direct Respond to . Instant messaging in this way , It's essentially a browser sending requests , A process by which a server accepts a request , By letting the client continue to request , Make the guest The client can simulate the change of data received from the server in real time . The advantage of this method is that it's simpler , Easy to understand . The drawback is that this approach needs to be built constantly ht tp Connect , Serious waste of server-side and client-side resources . As users increase , The pressure on the server side will increase , It's very unreasonable .

The basic idea of long polling is , First, the client initiates a request to the server , When the server receives the request from the client , The server will not respond directly , But first This request is pending , Then judge whether the data on the server side is updated . If there is an update , Then respond , If there's no data , It will return only after reaching a certain time limit . client JavaScript The response handler will process the information returned by the server , Request again , reestablish connection . Long polling is compared to short polling , its The advantage is that it obviously reduces a lot of unnecessary http Number of requests , By contrast, it saves resources . The disadvantage of long polling is , Connection suspension also leads to waste of resources .

SSE The basic idea of , The server uses streaming information to push information to the server . Strictly speaking ,http The protocol can't push information actively by the server . however , There's a workaround Method , That is, the server declares to the client , The next thing to send is streaming information . in other words , It's not a one-time packet sent , It's a data stream , It's going to be continuous Send it to me . At this time , The client will not close the connection , Will always wait for the server to send new data stream , Video playback is an example of this .SSE It's using this kind of machine system , Use streaming information to push information to the browser . It's based on http agreement , At present except IE/Edge, Other browsers support it . It's relative to the first two ways , No You need to build too much http request , By contrast, it saves resources .

All of the above three ways are essentially based on http Agreed , We can also use WebSocket Protocol to implement .WebSocket yes Html5 A new definition discussion , With the traditional http Different agreements , This protocol allows the server to actively push information to the client . Use WebSocket The disadvantage of the protocol is the configuration on the server side More complicated .WebSocket It's a full duplex protocol , That is to say, both sides of communication are equal , Messages can be sent to each other , and SSE The mode of communication is one-way , Can only Push information from the server to the client , If the client needs to send information, it belongs to the next one http Request the .

Implementation of a page operation will not refresh the whole page of the site , And can move forward in the browser 、 Respond correctly when backing off . Give your technical solution ?

answer : Compared to the jump of different pages ,AJAX It can be said that it greatly improves the browsing experience of users , It's a pleasure not to see the white screen between page changes . But a lot of the earlier ones AJAX The application does not support the browser's forward and backward , This results in users browsing anywhere on the site , Once refreshed, it will immediately return to its original position , And users can't switch the browsing history through the browser's forward and backward button .

For the first question , It's easy to solve , Just use cookie perhaps localStorage To record the status of the application , Read this status when refreshing the page , Then send the corresponding ajax Request to change the page . But the second problem is very troublesome , Let's talk about the solution of modern browser .

 

jQuery Interview questions

jquery characteristic , Talk about it jquery?

answer :

  • jQuery It's a lightweight model js frame ,jQuery The core js It's only a few dozen papers kb, Does not affect page load speed . And Extjs It's much lighter than that .
  • jQuery The selector of is very convenient to use , It's like I'm going to find someone dom Adjacent elements of an object js There may be several lines of code to write , and jQuery One line of code is done , Another example is that I want to change the color of the interlaced rows of a table ,jQuery It's one line of code .
  • jQuery The chain operation can write multiple operations in one line of code .
  • jQuery It also simplifies js operation css Code for , And the readability of the code is better than js stronger .
  • jQuery To simplify the AJAX operation , The background only needs to return one JSON Format string can complete the communication with the foreground .
  • jQuery Basically compatible with the current mainstream browser , Don't worry about browser compatibility anymore .
  • jQuery There are rich third-party plug-ins , for example : Tree menu 、 Date control 、 Picture switching plug-in 、 Pop up windows and other components on the basic front page all have corresponding plug-ins , And use jQuery The effect of plug-in is very dazzling , And according to their own needs to rewrite and package plug-ins , Simple and practical .
  • jQuery High scalability ,jQuery Provides extended interfaces :jQuery.extend(object), Can be in jQuery Add new functions to the namespace of .jQuery All plug-ins of are developed based on this extension interface .

jquery Objects and dom How are objects converted ?

answer :

  • [0] Can be converted to DOM object
  • $(domObject) Can be converted to jQuery object

jquery How to convert an array to json character string , And then convert it back ?

answer :

    $.fn.stringifyArray = function(array) {
    	return JSON.stringify(array)
    }
    $.fn.parseArray = function(array) {
    	return JSON.parse(array)
    }

And then call :

    $("").stringifyArray(array)

jQuery Have you seen the source code of ? Can you give a brief overview of its implementation principle ?

answer :

1、 Closure mechanism ;

//  The following is taken from  jquery  Source code fragment 
(function( window, undefined ) {
/*  Source content  */
})( window );

This little bit of code above comes from 1.9.0 among jquery Source code , It is a pollution-free environment JS Standard writing of plug-ins , The technical term is closure . Think of it simply as a function , Unlike ordinary functions , This function has no name , It will be carried out immediately

We change the variables in it into local variables , This can not only increase the running speed , More importantly, we are quoting jquery Of JS When you file , Not because jquery There are too many variables in it , And with other JS Frame variable naming conflicts ; The variable declaration in the closure does not contaminate the external global variables ;;

2、 As a global attribute ;

window.jQuery = window.$ = jQuery;

This sentence defines what we define in closures jQuery Object is exported as a global variable jQuery and $, So we can use it externally jQuery and $.

window By default JS Context , So bind the object to the window above , It is equivalent to becoming a global variable in the traditional sense ,

3、 Core functionality , It's a selector ;

First we enter jquery Source code , It's easy to find jquery Object declaration , I'll find out after reading it , It turns out that our jquery Object is init object .


    jQuery = function( selector, context ) {
    return new jQuery.fn.init( selector, context, rootjQuery );
    }

It's here jQuery.fn Such a thing , Its origin can be found in jquery Source code found in , It actually represents jQuery Prototypes of objects .


    jQuery.fn = jQuery.prototype;
    jQuery.fn.init.prototype = jQuery.fn;

These two words , The first sentence puts jQuery The prototype of the object is assigned to the fn attribute , The second sentence put jQuery The prototype of the object is assigned to the object init Prototypes of objects . in other words ,init Objects and jQuery Having the same prototype , So we went back up there init object , Just like jQuery Objects have the same properties and methods .

We're not going to go into it init The logic and implementation of this method , But what we need to know is ,jQuery It's really just the DOM The object is wrapped in a layer , And look for one or more DOM The object is sizzle I'm responsible for ,

jQuery Objects have many properties and methods ; For attributes , We need to focus on only one attribute , Namely [0] attribute ,[0] In fact, it's original DOM object .

A lot of times , We are jQuery and DOM When switching between objects, you need to use [0] This attribute .

As can be seen from the screenshots ,jQuery In fact, the object is mainly the original DOM Objects exist [0] The location of , And added a series of simple methods to it .

This index 0 We can take a simple look at its origin from a small piece of code , Here is init A short pair of methods DOMElement Object as the source code of the selector .


    // Handle $(DOMElement)
    if ( selector.nodeType ) {
    /*  You can see , There will be  DOM  Object is assigned to  jQuery  Object's  [0]  This position  */
    this.context = this[0] = selector;
    this.length = 1;
    return this;
    }

This small piece of code can be found in jquery Source code found in , It deals with the incoming selection parameter, which is a DOM About the object .

You can see , It's obvious inside that jQuery Object index 0 and context attribute , It's all given to DOM object

. The code doesn't just illustrate that , It also shows that , We use $(DOMElement) You can put a DOM Object to jQuery object , Thus, it can be obtained by transformation jQuery A simple method of selecting object .

4、ready Method

$(function(){}) Or is it ready Method ;

The implementation is similar to jquery Of ready The effect of this method can be easily achieved , Its implementation principle is , Maintain an array of functions , And then I kept judging DOM Whether the loading is finished , If the load is complete, all the functions in the array are triggered .

Following this idea ,LZ Take a little example I wrote a long time ago , Let's show you .

(function( window, undefined ) {
var jQuery = {
isReady:false,//  Identification of whether the document loading is complete 
readyList:[],//  Sequence of functions 
//onload  Event implementation 
ready : function(fn){
//  If it's a function , Add to function sequence 
if(fn && typeof fn == 'function' ){
jQuery.readyList.push(fn);
}
//  Document loading completed , Execution function sequence .
if(jQuery.isReady){
for(var i = 0;i < jQuery.readyList.length ;i++){
fn = jQuery.readyList[i];
jQuery.callback(fn);
}
return jQuery;
}
},
//  Callback 
callback : function(fn){
fn.call(document,jQuery);
}
};
//  Export object 
window.$ = window.jQuery = jQuery;
//  Judge whether the loading is completed or not 
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));

This code is LZ From the previous example , Its implementation logic is very simple , But it can achieve jQuery Of ready Effect of the method ,

5、extend Method

To put it simply, two extend Common ways to use methods .

  • 1、 Use jQuery.fn.extend You can extend the jQuery object , Use jQuery.extend You can extend the jQuery, The former is similar to adding normal methods to a class , The latter is similar to adding static methods to a class .
  • 2、 Two extend If there are two methods object Parameters of type , Then the following parameter object properties will be extended to the first parameter object , When expanding, you can add another boolean The parameter controls whether to copy in depth .

jquery find,children,filter The difference between ?

answer :

  • filter It's an operation on its own set elements ,
  • children Is the retrieval of child elements ,
  • find It's the retrieval of its descendant elements

.children(selector) The method is to return all child elements of each element in the set of matching elements ( Only sons ). Parameters can be chosen , Adding parameters means filtering through the selector , Filter elements .

.find(selector) The method is to return the descendants of each element in the set of matching elements . Parameter is required , Can be a selector 、jquery Objects can be used to filter elements .

.find() And .children() The method is similar to , The difference is that the latter only follows DOM The tree traverses down a single level . there children, I understand it as a son , Only at the son level .

jQuery How is the queue implemented ? Where can queues be used ?

answer :jQuery In the core , There is a set of queue control methods , This set of methods consists of queue()/dequeue()/clearQueue() There are three methods , Its control over functions that need to be executed continuously and sequentially can be said to be simple and easy , Mainly used in animate () Method ,ajax And other events to be executed in chronological order .

First, explain the meaning of each method .

queue(name,[callback]): When only one parameter is passed in , It returns and points to the queue of the first matching element ( Will be an array of functions , The default queue name is fx); When two parameters are passed in , The first parameter still defaults to fx The name of the line , The second parameter is divided into two cases , When the second argument is a function , It will add a function at the end of the queue of matched elements . When the second argument is an array of functions , It replaces the queue of matching elements with a new queue ( Function array ). Probably , It's a bit confusing to understand .

dequeue(name): That's easy to understand , Is to remove a queue function from the front end of the queue , And execute it .

clearQueue([queueName]): This is a 1.4 New method . Clear all queues on the object that have not been executed . Parameters can be chosen , The default is fx. But I don't think it's very useful , use queue() Method to pass in the second parameter of two parameters clearQueue Method .

Now? , We want to achieve such an effect , It's marked with 1 to 7 The number square of , Ask the seven squares to fall from left to right ; After writing

; If at this time , You want to change the execution order of one or another , such as , You want 5 Fall down and start falling again 3, Or new 8 to 15 Eight squares , What do I do ?

Rewrite it ? Be careful of Ji's change inside ? obviously , We need another simple and convenient way to achieve this effect , That's it jQuery Queue control method .;

thus , Doesn't it look more concise . How to achieve ?

  1. Create a new array , Put the animation functions in sequence ( So change the order , Is it more convenient to add new animation ?);
  2. use queue Add this set of animation function array to slideList In line ;
  3. use dequeue Take out slideList First function in queue , And execute it ;
  4. Initial execution of the first function .

as for clearQueue() Method , Not much , The stop button in the demo calls clearQueue() Method , Of course, you can use queue() Method to replace the current function queue with [] Empty array implementation ( I recommend replacing empty arrays ., More intuitive ).

jQuery And jQuery UI What's the difference ?

answer :

  • jQuery It's a js library , The main function provided is selector , Property modification and event binding, etc .
  • jQuery UI It is in jQuery On the basis of , utilize jQuery Scalability , Designed plug-ins .
    • Provides some common interface elements , Like dialog boxes 、 Drag behavior 、 Changing size, behavior, etc

jQuery and Zepto The difference between ? Respective use scenarios ?

answer :zepto Mainly used on mobile devices , Only newer browsers are supported , The advantage is that the amount of code is relatively small , The performance is better .

jquery Mainly good compatibility , You can run in all kinds of pc, Mobile , The advantage is that it's compatible with all kinds of browsers , The disadvantage is that the code is large , Also consider compatibility , The performance is not good enough .

jq I've noticed that it's always , All its 2.x Version does not support ie6 7 8 Of

in the light of jQuery Optimization of performance ?

answer :

  • be based on Class The selective performance of Id Selectors are expensive , Because you need to traverse all DOM Elements .
  • Frequently operated DOM, Cache before operation . use jQuery Better chain call of .
    • such as :var str=$("a").attr("href");
  • for loop

    for (var i = size; i < arr.length; i++) {
    
    }

     

for Loop each time the loop looks up the array (arr) Of length attribute , Set a variable to store the number at the beginning of the loop , Can make the cycle run faster :


    for (var i = size, length = arr.length; i < length; i++) {

    }

jQuery An object can bind multiple events at the same time , How this is achieved ?

answer :


    $ele.on('eventName', handle1);
    $ele.on('eventName', handle2);
    $ele.on('eventName', handle3);

Actually $ele Elemental eventName Event has an array of handler functions Put one inside at a time handle, It's the first out type

That's the stack , Then, when the event is triggered, it is executed once

The monitoring above is equivalent to


    $ele.eventHandle['eventName'] = [];
    $ele.eventHandle['eventName'].push(handle1);
    $ele.eventHandle['eventName'].push(handle2);
    $ele.eventHandle['eventName'].push(handle3);

then $ele.trigger('eventName') When triggered , Take the processing function from the stack and execute it


    while($ele.eventHandle['eventName'].length) {
    handle = $ele.eventHandle['eventName'].pop();
    handle();
    }

First listen last execute ;

 

 

 

 

 

 

Vue.js Interview questions

Vue.js The hook of routing ⼦ function ?

answer : Home page can control navigation jump , beforeEach , afterEach etc. ,⼀ like ⽤ On the page ⾯ title Modification of .⼀ You need to log in to adjust ⻚⾯ The redirection function of .

  • beforeEach There are mainly 3 Parameters to , from , next .
  • to : route I'm going to ⼊ Of ⽬ Route object .
  • from : route The route that the current navigation is about to leave .
  • next : function ⼀ Be sure to tune ⽤ The ⽅ Law resolve This hook ⼦. Of board ⾏ The effect depends on next ⽅ The tone of law ⽤ Parameters . Can control the jump of the web page

vuex What is it? ? How to make ⽤? What kind of functional scenario makes ⽤ it ?

answer :

  • only ⽤ The state to be read is concentrated in store in ; Changing state ⽅ This is to submit mutations , It's a synchronous thing ; Asynchronous logic should be encapsulated in action in .
  • stay main.js lead ⼊ store , notes ⼊. New ⼀ individual ⽬ record store , … export
  • Scene has : single ⻚ Should be ⽤ in , State between components 、⾳ Music play 、 The login status 、 Add ⼊ shopping ⻋
  • state : Vuex send ⽤ single ⼀ State tree , That is, every one should ⽤ It will only contain ⼀ individual store example , Dan Dan ⼀ state
  • Tree and modularity do not conflict . Status of stored data , It can't be modified directly ⾥⾯ The data of .
  • mutations : mutations Defined ⽅ Law dynamic modification Vuex Of store The state or data in
  • getters : similar vue Calculated attributes of , The main ⽤ To filter ⼀ Some data .
  • action : actions It can be understood that by mutations ⾥⾯ It's about ⾥ Data ⽅ Methods become asynchronous data processing ⽅ Law , In short, asynchronous operation of data . view Layers pass through store.dispath To distribute action
  • modules : term ⽬ When it's particularly complicated , You can make every ⼀ Modules have ⾃⼰ Of state 、mutation 、 action 、 getters , Make the structure ⾮ Always clear ,⽅ Then manage

Vue.js How to make CSS Start only in the current component ⽤?

answer : Will be the current component of <style> It is amended as follows <style scoped>

Vue.js Instructions v-el Works of ⽤ What is it? ?

answer : Provide ⼀ It's on the page ⾯ That already exists on DOM Elements as Vue Example mount ⽬ mark . It can be CSS Selectors , It can also be ⼀ individual HTMLElement example ,

stay Vue.js Chinese envoy ⽤ Plug in steps ?

answer :

  • Mining ⽤ ES6 Of import … from … Grammar or CommonJS Of require() ⽅ Fayin ⼊ plug-in unit
  • send ⽤ overall situation ⽅ Law Vue.use( plugin ) send ⽤ plug-in unit , It can be transmitted ⼊⼀ Options object Vue.use(MyPlugin, { someOption: true })

Vue.js Jump between routes ?

answer : declarative ( Tag jump )

<router-link :to="index">

programmatic ( js Jump )


    router.push('index')

Vue.js In the component data When can it be used ⽤ object ?

answer : Component copy ⽤ All component instances will share data , If data If it's the object , Will cause ⼀ A component modify data It will affect all other components later , So we need to data Write function , Every time ⽤ Tune in when you arrive ⽤ ⼀ New data are obtained by sub function . When we make ⽤ new Vue() Of ⽅ When you're in the mood ,⽆ On how we will data It can be set to object or function So , because new Vue() Of ⽅ The formula is ⽣ become ⼀ Root components , The component will not duplicate ⽤, There is no sharing data The situation of the

Vue-Router What are the navigation guards in China ?

answer : Complete navigation analysis process

  1. Navigation is triggered .
  2. Call the leave guard in the deactivated component .
  3. Call global beforeEach The guards .
  4. Called in a reused component beforeRouteUpdate The guards (2.2+).
  5. Call... In routing configuration beforeEnter.
  6. Resolve asynchronous routing components .
  7. Called in the active component beforeRouteEnter.
  8. Call global beforeResolve The guards (2.5+).
  9. Navigation confirmed .
  10. Call global afterEach hook .
  11. Trigger DOM to update .
  12. Call... With the created instance beforeRouteEnter Pass it to next Callback function for .

Vue.js ajax In which lifecycle is the request placed ?

answer :

  • stay created When , In the view dom It's not rendered , So at this time, if you go directly to exercise dom node , Cannot find related element
  • stay mounted in , Because of this time dom It's already rendered , So you can do it directly dom node

In general, they are put in mounted in , Guarantee the unity of logic , Because the lifecycle is synchronized ,ajax It's asynchronous

Vue.js How to separate the same logic from ?

answer :Vue.mixin usage Give components every lifecycle , Functions and so on are mixed with some common logic

    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) { //  Recursive merge extends
          parent = mergeOptions(parent, child.extends, vm)
        }
        if (child.mixins) { //  Recursive merge mixin
          for (let i = 0, l = child.mixins.length; i < l; i++) {
            parent = mergeOptions(parent, child.mixins[i], vm)
          }
        }
      }
      const options = {} //  The combination of attributes and life cycle 
      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 merging strategies to merge 
        options[key] = strat(parent[key], child[key], vm, key)
      }
      return options
    }

Vue.js Common performance optimizations in ?

answer :1. Coding optimization :

  • 1. Don't put all the data in the database data in ,data The data in will increase getter and setter, Will collect the corresponding watcher

  • 2.vue stay v-for You need to use an event proxy to bind events to each element

  • 3.SPA Page adoption keep-alive Cache components

  • 4. Split components ( Improve reusability 、 Increase code maintainability , Reduce unnecessary rendering )

  • 5.v-if The duty of false Internal instructions will not be executed , It has blocking function , In many cases v-if replace v-show

  • 6.key Guarantee uniqueness ( Default vue Will adopt in place reuse strategy )

  • 7.Object.freeze Freezing data

  • 8. Rational use of route load 、 Asynchronous component

  • 9. Use as far as possible runtime Runtime version

  • 10. Data persistence ( Shake proof 、 throttle )

2.Vue Load performance optimization :

3. User experience :

  • app-skeleton Skeleton screen
  • app-shellapp shell
  • pwa

4.SEO Optimize :

  • Pre rendering plug-in prerender-spa-plugin
  • Server rendering ssr

5. Package optimization :

  • Use cdn To load the third-party module
  • Multithreading packaging happypack
  • splitChunks Withdraw public documents
  • sourceMap Generate

6. cache , Compress

  • Client cache 、 Server cache
  • Server side gzip Compress

Talk about you being right Vue.js Of MVVM Understanding of principles ?

answer : Tradition MVC

Conventional MVC refer to

  • M The business model ,Model( Model )
  • V User interface ,View( View )
  • C Controller ,Controller( controller )

Use MVC The goal is to M and V Implementation code separation of , So that the same program can use different forms of expression .

The user operation will request the server route , The route will call the corresponding controller to handle , The controller gets the data . Return the results to the front end , Page re rendering

MVVM

MVVM yes Model-View-ViewModel Abbreviation

  • Model Representative data model , It can also be in Model Business logic for defining data modifications and operations .
  • View representative UI Components , It is responsible for transforming the data model into UI show .
  • ViewModel Monitor model data changes and control views ⾏ by 、 Handle ⽤ User interaction , The simple understanding is ⼀ Synchronization View and Model The object of , Connect Model and View

The traditional front end will manually render the data to the page ,MVVM The mode does not require manual operation by the user dom Elements ;

Bind data to viewModel On the floor , The data is automatically rendered to the page , View changes are notified viewModel layer Update data .

ViewModel It's us MVVM The bridge in the pattern .

stay MVVM Under the architecture , View and Model There is no direct connection ,⽽ It's through ViewModel Into the ⾏ Interaction , Model and ViewModel The interaction is two-way , because this View The changes in the data will be synchronized to Model in ,⽽Model Changes in data will also ⽴ That is to say Should arrive at View On .

ViewModel Through two-way data binding View Layer and the Model The layers are connected ,⽽ View and Model Synchronization between ⼯ It's all about ⾃ Dynamic ,⽆ Need to be ⼈ by ⼲ Involve , So open The sender only needs to focus on the business logic , Unwanted ⼿ Move the operation DOM, You don't need to pay attention to the same data state Step question , Complex data state maintenance completely by MVVM Laitong ⼀ management .

Please say Vue.js The principle of responsive data ?

answer :

  • 1. emphasis :Object.defineProperty
  • 2. Default Vue When initializing data , Will give data Use of properties in Object.defineProperty Redefine all properties , When the page gets the corresponding property . Dependency collection will be conducted ( Collect the current component's watcher) If the property changes, the related dependency will be notified to update .
    Object.defineProperty(obj, key, {
        enumerable: true,
        configurable: true,
        get: function reactiveGetter () {
          const value = getter ? getter.call(obj) : val
          if (Dep.target) {
            dep.depend() // **  Collection dependency  ** /
            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() /** Notify dependent to update **/
        }
      })

Vue.js Principles of template compilation ?

answer : take template Turn it into render function

    function baseCompile (
      template: string,
      options: CompilerOptions
    ) {
      const ast = parse(template.trim(), options) // 1. Convert the template to ast Grammar tree 
      if (options.optimize !== false) {           // 2. Optimization tree 
        optimize(ast, options)
      }
      const code = generate(ast, options)         // 3. Make trees 
      return {
        ast,
        render: code.render,
        staticRenderFns: code.staticRenderFns
      }
    })
    const ncname = `[a-zA-Z_][\\-\\.0-9_a-zA-Z]*`; 
    const qnameCapture = `((?:${ncname}\\:)?${ncname})`;
    const startTagOpen = new RegExp(`^<${qnameCapture}`); //  Regular at the beginning of a label   The captured content is the tag name 
    const endTag = new RegExp(`^<\\/${qnameCapture}[^>]*>`); //  Match at the end of the tag   </div>
    const attribute = /^\s*([^\s"'<>\/=]+)(?:\s*(=)\s*(?:"([^"]*)"+|'([^']*)'+|([^\s"'=<>`]+)))?/; //  Matching properties of 
    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 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(${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}}`;
    //  Packaged as functions 
    let renderFn = new Function(render);
    console.log(renderFn.toString());

sketch Vue.js in diff Algorithm principle ?

answer :

  • 1. First compare the same level , Comparing child nodes
  • 2. First of all, judge whether one party has a son and the other has no son
  • 3. We all have sons
  • 4. Recursively compare child nodes
    const oldCh = oldVnode.children //  Old son  
    const ch = vnode.children  //  The new son 
    if (isUndef(vnode.text)) {
        if (isDef(oldCh) && isDef(ch)) {
            //  Compare kids 
            if (oldCh !== ch) updateChildren(elm, oldCh, ch, insertedVnodeQueue, removeOnly)
        } else if (isDef(ch)) { //  The new son has   The old one didn't 
            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 a new one   Just delete 
            removeVnodes(oldCh, 0, oldCh.length - 1)
        } else if (isDef(oldVnode.text)) {  //  The old one has text   New no text 
            nodeOps.setTextContent(elm, '') //  Empty the old 
        }
    } else if (oldVnode.text !== vnode.text) { //  Different text replacement 
        nodeOps.setTextContent(elm, vnode.text)
    }
    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
        const canMove = !removeOnly
        if (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)
        }
      }

 Vue.js Of v-model Realization principle , And how to customize v-model?

answer : Component's v-model yes value+input Method The grammar sugar of

    <el-checkbox :value="" @input=""></el-checkbox>
    <el-checkbox v-model="check"></el-checkbox>

You can redefine it yourself v-model The meaning of

    Vue.component('el-checkbox',{
        template:`<input type="checkbox" :checked="check" @change="$emit('change',$event.target.checked)">`,
        model:{
            prop:'check', //  Change default value Name 
            event:'change' //  Change the default method name 
        },
        props: {
            check: Boolean
        },
    })

Will be the component of v-model The default is converted 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"
    //         }
    //     })
    // }
    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.value
      const 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
      }
    }

Native v-model, Different events and properties will be generated according to different tags

    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
            }
        }
    })
    }
    */

Compile time : Different tags resolve different content

    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
      }

Runtime : Will deal with some input method problems with 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
            }
          }
        }
      }

Vue.js Life cycle of components ?

answer : The total is divided into 8 Before phase creation / after , load ⼊ front / after , Before updating / after , Before destruction / after

  • Before creation / after : stay beforeCreate Stage , vue Mount elements for instances el And data objects data All for undefined , Not initialized yet . stay created Stage , vue The data object of the instance data With ,el also No,
  • load ⼊ front / after : stay beforeMount Stage , vue Example of $el and data It's all initialized , But it's still virtual before mounting dom node , data.message Not yet replaced . stay mounted Stage , vue Instance mount completed , data.message Successful rendering .
  • Before updating / after : When data When the change , Will trigger beforeUpdate and updated ⽅ Law
  • Before destruction / after : Holding on to ⾏ destroy ⽅ After the law , Yes data The periodic function is no longer triggered by the change of , That at this time vue Instance has removed event listening and dom The binding of , however dom Structure still exists

To know when each lifecycle is called

  • beforeCreate After the instance is initialized , The data observed (data observer) Called before .
  • created The instance is called after it has been created . In this step , The instance has completed the following configuration : The data observed (data observer), Operations on properties and methods , watch/event Event callback . Nothing here $el
  • beforeMount Called before the mount begins : dependent render The function is called for the first time .
  • mounted el Newly created vm.$el Replace , And mount it to the instance to call the hook. .
  • beforeUpdate Call... When data is updated , It happens in the virtual DOM Before re rendering and patching .
  • updated Virtual due to data changes DOM Re rendering and patching , The hook is called after this .
  • beforeDestroy Call before instance destruction . In this step , Instance is still fully available .
  • destroyed Vue Call after instance destruction . After calling ,Vue Everything indicated by the instance is unbound , All event listeners will be removed , All child instances will also be destroyed . This hook is not called during server-side rendering .

Master what can be done within each life cycle

  • created The instance has been created , Because it's the first trigger, you can do some data , Requests for resources .
  • mounted The instance has been mounted , There can be some DOM operation
  • beforeUpdate You can further change the state in this hook , This does not trigger an additional re render process .
  • updated Can be executed depending on DOM The operation of . But in most cases , You should avoid changing state during this period , Because this can lead to infinite cycles of updates . This hook is not called during server-side rendering .
  • destroyed You can perform some optimizations , Clear timer , Unbind event

What is? vue⽣ Life cycle ?

answer : Vue The process from creation to destruction of an instance , Namely ⽣ Life cycle . Create... From the beginning 、 Initialization data 、 Compiling templates 、 mount Dom→ Rendering 、 to update → Rendering 、 Destruction, etc ⼀ Series process , be called Vue Of ⽣ Life cycle .

vue⽣ Life cycle work ⽤ What is it? ?

answer : its ⽣ There are multiple events in the lifecycle ⼦, Let's control the whole Vue Instance process is easier to form a good Logic .

vue⽣ The total life cycle is ⼏ Stages ?

answer : It can be divided into 8 Stages : Before creation / after 、 load ⼊ front / after 、 Before updating / after 、 Before destruction / After destruction .

The first ⼀ Next page ⾯ What will load trigger ⼏ A hook ⼦?

answer : It will trigger ⾯ this ⼏ individual beforeCreate 、 created 、 beforeMount 、 mounted .

DOM In which cycle the rendering is done ?

answer : DOM Rendering in mounted China has finished

Describe the component rendering and update process ?

answer : When rendering components , Will pass Vue.extend Method to construct the constructor of the subcomponent , And instantiate . Finally, manually call $mount() Mount . When the component is updated patchVnode technological process . The core is diff Algorithm

Vue.js How components communicate and what are the ways ?

answer :

  • Father son communication Father -> Son through props、 Son -> Father $on、$emit
  • How to get parent-child component instances $parent、$children
  • Provide data sub components in the parent component for consumption Provide、inject
  • Ref Get the instance's way to call the component's properties or methods
  • Event Bus Achieve cross component communication
  • Vuex State management realizes communication

1. ⽗⼦ signal communication

⽗ Components through props Transfer data to ⼦ Components ,⼦ Components through emit Send event to pass data to ⽗ Components , These two kinds of ⽅ The most common form is ⽤ Of ⽗⼦ How to realize communication .

such ⽗⼦ signal communication ⽅ This is a typical one-way data flow ,⽗ Components through props To transfer data ,⼦ Components cannot Directly modifying props ,⽽ You have to send events through ⽅ To inform ⽗ Components modify data .

The other two ⽅ It can also make ⽤ Grammatical sugar v-model To achieve directly , because v-model By default, it resolves to be known as value Of prop And called input Events . This grammatical sugar is ⽅ Expression is a typical bidirectional binding , often ⽤ On UI Controls , But at its root , Or through events ⽅ Farrang ⽗ Components modify data .

Of course, we can also visit $parent perhaps $children Object to access ⽅ Law and number According to the .

Besides, if you make ⽤ Vue 2.3 And above can also make ⽤ $listeners and .sync These two genera sex .

$listeners Attributes will ⽗ In the component ( Not included .native Decorator's ) v-on Event listener passed to ⼦ Components ,⼦ Components can be accessed through $listeners Come on ⾃ Define a listener .

.sync Attribute is a grammatical sugar , Can be very simple to achieve ⼦ Components and ⽗ Component communication

<!--⽗ In the component -->
<input :value.sync="value" />
<!-- The above is equivalent to -->
<input :value="value" @update:value="v => value = v"></comp>
<!--⼦ In the component -->
<script>
this.$emit('update:value', 1)
</script>

2. Brother component communication

In this case, you can find ⽗ In the component ⼦ Component implementation , That is to say this.$parent.$children , stay $children Through the component name Inquire about To the required component instance , Then enter ⾏ signal communication .

3. Communication across multi-level components

In this case, the ⽤ Vue 2.2 Newly added API provide / inject , although ⽂ It is not recommended to use ⽤ In the business , But if ⽤ If it's good, it's still very good ⽤ Of .

Suppose there is ⽗ Components A , Then there is ⼀ Across multiple levels ⼦ Components B

// ⽗ Components  A
export default {
provide: {
data: 1
}
}
// ⼦ Components  B
export default {
inject: ['data'],
mounted() {
// ⽆ On Cross ⼏ Layers can get ⽗ Component's  data  attribute 
console.log(this.data) // => 1
}
}

The ultimate solution ⼀ Communication problems

As long as you're not afraid of trouble , You can make ⽤ Vuex perhaps Event Bus Solve all the above communication situations .

why Vue.js Asynchronous rendering ?

answer : Because if you don't use asynchronous updates , Then each time the data is updated, the current component will be re rendered .

So for the sake of performance .Vue After this round of data update , To update the view asynchronously !

It's a bit 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, the watcher Put in a queue for batch update 
        }
    }
    export function queueWatcher (watcher: Watcher) {
      const id = watcher.id //  It's going to be the same watcher To filter 
      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 nextTick Method   Batch update 
        }
      }
    }

Vue.js in v-if and v-show The difference between ?

answer :

  • v-if If the condition is not true, it will not render the node where the current instruction is located dom Elements
  • v-show Just switch the current dom To show or hide

v-show It's just display: none and display: block Switch between .⽆ What are the initial conditions Will be rendered , after ⾯ Just switch CSS , DOM still ⼀ It's still there . So in general v- show There are changes in the initial rendering ⾼ The cost of , But the switching overhead is very high ⼩, More suitable for scenes with frequent switching .

v-if You have to say Vue The underlying compiles . When the property is initially false when , Components will not be rendered dye , Until the condition is true , And the destruction will be triggered when switching conditions / Mount components , So in general, when switching on Marketing ⾼, More suitable for scenes that don't often switch .

And based on v-if This kind of lazy rendering mechanism , You can render components when necessary , Reduce the whole ⻚⾯ Of Initial rendering overhead .

summary : v-if Render according to the condition , v-show yes display Of block or none ;

    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()
    }
    */
    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-show  The operation is pattern    It's defined 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'
        }
    }

Vue.js Why v-for and v-if It can't be used together ?

answer :v-for than v-if Has a higher priority , If used in combination, it will v-if Add a little bit of , Can cause 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);

Vue.js To realize hash Routing and history route ?

answer :

  • onhashchange
  • history.pushState

  • hash Pattern : In browser symbols “#” ,# as well as # after ⾯ The character of is called hash ,⽤ window.location.hash Read . characteristic : hash Although in URL in , But not included in HTTP In request ;⽤ To guide browser actions , Server side security ⽆⽤, hash No reloading ⻚⾯.

  • history Pattern :h istory Mining ⽤ HTML5 New features ; And it provides two new ⽅ Law :pushState() , replaceState() You can stack browser history ⾏ modify , as well as popState Event monitoring to status change

Vue.js Of action and mutation difference ?

answer :

  • mutation It's a synchronous update ( Whether the data is updated asynchronously will be detected internally )
  • action Asynchronous operations , Data can be obtained after adjustment. mutation Submit final data

Vue.js and react difference ?

answer : The same thing

all ⽀ a ssr , There are vdom , Component development , Realization webComponents standard , Data drive Move and wait

Difference

vue It's two-way data flow ( Of course, in order to achieve a single data stream ⽅ To manage component status , vuex There is a ), react It's a one-way data flow . vue Of vdom It's tracking the dependencies of each component , Does not render the entire component tree , react Whenever the state should be changed , All ⼦ Components will re-render

 

 

 

 

React.js Interview questions

React ⽣ Life cycle function ?

answer : stay V16 The edition quoted ⼊ 了 Fiber Mechanism . This mechanism ⼀ To a certain extent, it affected part of ⽣ life Periodic modulation ⽤, And it also leads to ⼊ New 2 individual API To solve the problem

In the previous version , If you have ⼀ A very complex composite component , Then the top-level components were changed Of state , So tune ⽤ The stack can be very tuned ⽤ Over the stack , Plus in the middle ⾏ It's a complicated operation , May lead to ⻓ Time blocking main thread , Bring bad ⽤ User experience . Fiber Just to solve the problem ⽽⽣Fiber Essentially, ⼀ Virtual stack frame , The new scheduler will follow the priority ⾃ By scheduling these frames , from ⽽ take The previous synchronous rendering was changed to asynchronous rendering , In the case that does not affect the experience, the piecewise calculation of the update for how to distinguish the priority , React Yes ⾃⼰ Of ⼀ Logic . It's very real-time for this kind of animation ⾼ East of ⻄, also Namely 16 ms You have to render ⼀ There is no guarantee in the case of Caton , React Every 16 ms ( within ) Pause ⼀ Next update , Return to continue rendering the animation , For asynchronous rendering , Now there are two stages to rendering : reconciliation and commit . The former process is OK Interrupted , The latter cannot be suspended , Meeting ⼀ Zhigeng New Territories ⾯ Until completion .

Initialization phase

  • getDefaultProps : Gets the default properties of the instance
  • getInitialState : Get the initialization state of each instance
  • componentWillMount : Component is about to be loaded 、 Render to ⻚⾯ On
  • render : The components are here ⾥⽣ Become virtual DOM node
  • omponentDidMount : Components are actually loaded

shipment ⾏ Medium state

  • componentWillReceiveProps : When a component is about to receive a property, call ⽤
  • shouldComponentUpdate : When a component receives a new property or state ( Can return false, Number received
  • It's not updated , Resistance ⽌ render transfer ⽤, after ⾯ Will not be continued ⾏ 了 )
  • componentWillUpdate : Component is about to be updated property and status cannot be modified
  • render : Component redraw
  • componentDidUpdate : Component updated

Destruction phase

  • componentWillUnmount : Components are about to be destroyed

because Reconciliation Stages can be interrupted , therefore Reconciliation Stage Can hold ⾏ Of ⽣ Life cycle function may appear tune ⽤ Many times , from ⽽ cause Bug . thus about Reconciliation Phasing ⽤ Of ⼏ A function , except shouldComponentUpdate outside , Others should be avoided ⽤, also V16 Also in the lead ⼊ New API To solve this problem .

getDerivedStateFromProps ⽤ To replace componentWillReceiveProps , This function initializes and update The time is adjusted ⽤

React in keys Works of ⽤ What is it? ?

answer :Keys yes React ⽤ To track which elements in the list have been modified 、 A secondary identifier that has been added or removed

In the development process , We need to guarantee the key In its sibling elements, there is only ⼀ sex . stay React Diff In the algorithm, React With the help of elements Key Value to determine whether the element was newly created or moved ⽽ Come on The elements of , from ⽽ Reduce unnecessary element re rendering . Besides ,React You need help Key Value to determine whether the element and Association of local state , So we must not ignore the transformation function Key Importance

React in refs Works of ⽤ What is it? ?

answer :

  • Refs yes React Security access provided to us DOM Element or a handle to a component instance
  • You can add ref Property then accepts the element in the callback function DOM Handle in tree , This value is used as the first step of the callback function ⼀ A parameter returns

React Native As opposed to the original ios and Android What are the advantages ?

answer :

  • 1. Performance is comparable to native APP
  • 2. Use JavaScript code , Just learn the language
  • 3. Most of the code is Android IOS All can be shared
  • 4. Component development , Code reuse is high
  • 5. It's like writing a web page , After modifying the code, you can automatically refresh , No need to compile slowly , Save a lot of compile wait time
  • 6. Support APP Hot update , Updates do not need to be reinstalled APP

shortcoming :

  • The memory consumption is relatively high
  • The version is not stable yet , Keep updating , There is no stable 1.0 edition

props and state Similarities and differences ?

answer :1. Whether it's props still state Changes , Will trigger render Re rendering of .

2. Can set the initial value by the corresponding initialization function of its own components .

Difference

1. Source of initial value :state The initial value of comes from its own getInitalState(constructor) function ;props From parent component or itself getDefaultProps( if key The former can cover the latter ).

2. Modify the way :state Only in its own components setState, Cannot be modified by parent component ;props Can only be modified by parent component , Cannot be modified in its own components .

3. Sub components :props Is the data flow passed from a parent component to a child component , This data flow can be passed to the descendant components ;state Represents the internal state of a component , Can only exist in its own components .


sketch flux thought ?

answer :Flux The most ⼤ characteristic , It's data ” Unidirectional flow ”.

  • ⽤ Users visit View
  • View issue ⽤ Household Action
  • Dispatcher received Action , requirement Store Into the ⾏ Update accordingly
  • Store After the update , issue ⼀ individual “change” event
  • View received “change” After the event , Update page ⾯

Tell me about you ⽤react What's the pit ?

answer :

  1. JSX When judging expressions , Need to force to boolean type

If you don't make ⽤ !!b Into the ⾏ Strong data type , It'll be on page ⾯⾥⾯ Output 0 .

  1. render() {
  2. const b = 0;
  3. return <div>
  4. {
  5. !!b && <div> This is a ⼀ paragraph ⽂ Ben </div>
  6. }
  7. </div>
  8. }
  1. Try not to componentWillReviceProps ⾥ send ⽤ setState, If ⼀ Make sure that ⽤, Then we need to judge Break the end condition , Otherwise it will appear ⽆ Limited rendering , Cause page ⾯ collapse

  2. Add... To the component ref When , Try not to use ⽤ Anonymous functions , Because when the component is updated , Anonymous functions are treated as new prop Handle , Give Way ref When the property receives a new function ,react The interior will be emptied first ref, That is to say, they will use null To return to Adjust the parameters first ⾏⼀ Time ref This props, Then execute the instance of the component ⾏⼀ Time ref, therefore ⽤ Anonymous functions do ref When , Sometimes go to ref After assignment, the property will be retrieved null

  3. Traverse ⼦ Node time , Don't ⽤ index As a component key Into the ⾏ Pass on ⼊

React performance optimization ⽅ case ?

answer :

  • rewrite shouldComponentUpdate To avoid unnecessary dom operation
  • send ⽤ production Version of react.js
  • send ⽤ key To help React Identify all... In the list ⼦ The most ⼩ change

stay shouldComponentUpdate Function, we can return Boolean values to determine whether the current component needs to be more new . This layer of code logic can be simply shallow ⽐ a ⼀ Now state And before state Are they the same? , also The component update can be triggered only when a value is updated .⼀ Generally speaking, it is not recommended to treat ⽐ At present state And Before state Are they the same? , Because component update triggers can be very frequent , Such integrity is right for ⽐ There will be performance overhead spot ⼤, There may be a situation where the gain is not worth the loss

Of course, if you really want to be complete to ⽐ At present state And before state Are they the same? , And it doesn't affect performance ⾏ It works , Can pass immutable perhaps immer These libraries come ⽣ Become immutable objects . This kind of library is very useful for do ⼤ In terms of large-scale data, it will improve good performance , also ⼀ If you change the data, you will ⽣ become ⼀ A new object , Yes ⽐ Before and after state whether ⼀ To ⽅ There will be more , At the same time, I also recommend reading immer Source code implementation

In addition, if it's only shallow ⽐ a ⼀ Next , You can make ⽤ PureComponent , The bottom layer is the realization of shallow ⽐ a state

    class Test extends React.PureComponent {
        render() {
            return (
                <div>
                    PureComponent
                </div>
            )
        }
    }

At this point, you may consider that function components cannot make ⽤ such ⽅ Yes , If you make ⽤16.6.0 Later versions , You can make ⽤ React.memo To achieve the same function

    const Test = React.memo(() => (
        <div>
            PureComponent
        </div>
    ))

Through this kind of ⽅ Then we can realize shouldComponentUpdate The light of ⽐ a ,⼜ Can make ⽤ Function component

React monitor ?

answer :

Front end monitoring ⼀ There are three kinds of , Respectively ⻚⾯ Buried point 、 Performance monitoring and exception monitoring .

this ⼀ In this chapter, we will learn about these monitoring related topics in the future , But there's no code involved , Just let ⼤ Home to know before The end monitor should ⽤ what ⽅ Implementation of . After all ⼤ Some companies just make ⽤ To the third ⽅ Monitoring of ⼯ have ,⽽ Is not a choice ⾃ ⼰ Making a wheel ⼦

1 page ⾯ Buried point

page ⾯ The burial point should be ⼤ Home is the most common monitor ,⼀ At least the following will be monitored ⼏ Data :

  • PV / UV
  • When you stay ⻓
  • Source of flow
  • ⽤ User interaction

For this ⼏ Class Statistics ,⼀ How to realize it ⼤ It can be divided into two types , Respectively ⼿ Write buried points and ⽆ bury Dot ⽅ type .

Believe in the second ⼀ Kind of ⽅ So is the formula ⼤ Home is the most common ⽤ Of ⽅ type , Sure ⾃ The master selects the data to be monitored, and then in the corresponding place ⽅ Write ⼊ Code . such ⽅ It's very flexible ⼤, But only ⼀ The drawback is that ⼯ More work is done ⼤, Every place to be monitored ⽅ You have to plug in ⼊ Code .

another ⼀ Kind of ⽆ Buried ⽅ There is no need for developers ⼿ It's written down a little bit ,⽽ It is to count all the events and report them regularly . such ⽅ Although there is no front ⼀ Kind of ⽅ It's complicated , But because it counts all the events , So we need to filter out what we need later data .

2 Performance monitoring

Performance monitoring can help developers to understand in a variety of real environments ,⻚⾯ What is the performance of .

For performance monitoring , We can use it directly ⽤ browser ⾃ Band Performance API To realize this work can .

For performance monitoring , In fact, we just need to adjust ⽤

performance.getEntriesByType(‘navigation’) this ⾏ The code is ⾏ 了 . Yes , You read that right ,⼀ ⾏ Code, we can get ⻚⾯ Detailed performance related information in

We can find this ⾏ The code returns ⼀ An array , There's a lot of information inside , From the data It started with ⽹ Transmit from the network to ⻚⾯ After loading, Chengdu provides the corresponding data

3 Abnormal monitoring

For anomaly monitoring , The following two types of monitoring are essential , They are code error and connection ⼝ Abnormal report . For code transport ⾏ error , The usual way is to make ⽤ window.onerror Intercept error reports . The ⽅ Dharma can intercept ⼤ Part of the detailed error information , But there are exceptions

  1. For cross domain code operation ⾏ The error will show Script error . In this case, we need to give script label add to crossorigin attribute

  2. For some browsers, the tone may not be displayed ⽤ The stack information , This can be done by arguments.callee.caller To do stack recursion

For asynchronous code , You can make ⽤ catch Of ⽅ Catch an error .⽐ Such as Promise You can make ⽤ catch function , async await You can make ⽤ try catch

But pay attention to online transportation ⾏ All the code is compressed , It needs to be packed ⽣ become sourceMap ⽂ It is convenient to debug

The captured errors need to be uploaded to the server , Usually it can be done by img Labeled src launch ⼀ A request .

And then ⼝ Anomalies are relatively simple , You can list the error status codes .⼀ Once such a status code appears, you can With ⽴ That is, the report is wrong . Pick up ⼝ Exception reporting enables development ⼈ The receptionist quickly knows which ones are available ⼝ There is ⼤⾯ The report of product wrong , In order to quickly fix the problem .

React.js signal communication ?

answer :1. ⽗⼦ signal communication

⽗ Components through props Transfer data to ⼦ Components ,⼦ Components are tuned by ⽤⽗ The function from the component passes data to ⽗ Components , These two kinds of ⽅ The most common form is ⽤ Of ⽗⼦ How to realize communication .

such ⽗⼦ signal communication ⽅ This is a typical one-way data flow ,⽗ Components through props To transfer data ,⼦ Components cannot Directly modifying props , ⽽ It has to be adjusted ⽤⽗ Components of functions ⽅ To inform ⽗ Components modify data .

2. Brother component communication

In this case, it can be done through a common ⽗ Components and functions to manage events .⽐ Among them ⼀ individual Brother component tune ⽤⽗ Component passed by the event function modification ⽗ State in component , then ⽗ Components will The state is passed to another ⼀ A brother component

3. Communication across multi-level components

If you make ⽤ 16.3 In the above version , In this case, the ⽤ Context API

//  establish  Context, It can be passed at the beginning ⼊ value 
const StateContext = React.createContext()
class Parent extends React.Component {
render () {
return (
// value  That is to say ⼊ Context  The value in 
<StateContext.Provider value='yck'>
<Child />
</StateContext.Provider>
)
}
}
class Child extends React.Component {
render () {
return (
<ThemeContext.Consumer>
//  Extract value 
{context => (
name is { context }
)}
</ThemeContext.Consumer>
);
}
}

4. Any component

such ⽅ The formula can be expressed by Redux perhaps Event Bus solve , If you're not afraid of other troubles word , You can make ⽤ such ⽅ To solve all the above communications .

React Event mechanism ?

answer :React Actually ⾃⼰ Realized ⼀ A set of event mechanisms ,⾸ Let's think about it first ⼀ Here's the code

const Test = ({ list, handleClick }) => ({ list.map((item, index) => ( <span onClick={handleClick} key={index}>{index}</span> )) })

The above code must be similar ⼤ I often write about , But have you ever considered whether the click event is bound to every ⼀ A label On ? Of course not , JSX The events written on are not bound to the corresponding real DOM On ,⽽ It's through events Acting ⽅ type , Put all the events together ⼀ Bound to document On . In this way ⽅ It not only reduces the memory consumption Consumption , It can also be used when components are mounted and destroyed ⼀ Subscribe and remove events .

In addition to bubbling to document The events on the Internet are not the original events ⽣ Browser Events ,⽽ yes React ⾃⼰ Realized synthesis event ( SyntheticEvent ). So if we don't want events to bubble , transfer ⽤ event.stopPropagation yes ⽆ Effective ,⽽ It should be adjusted ⽤ event.preventDefault

The ⽬ What is it ? On the whole, in my opinion, there are two advantages , Namely :

  1. Composite event ⾸ First, it smoothes out the compatibility between browsers , And this is ⼀ Cross browser origin ⽣ Event wrapper , Fu To cross browser development can ⼒

  2. For the original ⽣ For browser events , The browser creates ⼀ An event object . If you have a lot of events listen , Then you need to allocate a lot of event objects , cause ⾼ Memory allocation problem . But for synthetic events say , Yes ⼀ Event pools ⻔ To manage their creation and destruction , When events need to be enabled ⽤ when , From the pool ⼦ Zhongfu ⽤ object , After the event callback ends , The properties on the event object are destroyed , from ⽽ It's convenient to reply next time ⽤ Event object .

 

Tool interview questions

git And svn What's the difference ?

answer :git and svn The biggest difference is git It's distributed , and svn It's centralized . So we can't use it offline anymore svn. If the server Problems arise , We can't use it svn Come and submit our code .

svn The branch in is a complete copy of the entire version library , and git The pointer is a commit that points to , therefore git Branch creation is more expensive and less expensive And changes in the branches don't affect other people .svn The change of the branch will affect all people .

svn The instruction of is relative to git It's simpler , Than git Easier to use .

Frequently used git command ?

answer :

    git init                     //  newly build  git  The code base 
    git add                      //  Add the specified file to the staging area 
    git rm                       //  Delete workspace file , And put the deletion in the staging area 
    git commit -m [message]      //  Submit staging area to warehouse area 
    git branch                   //  List all branches 
    git checkout -b [branch]     //  Create a new branch , And switch to the branch 
    git status                   //  Show changed documents 

git pull and git fetch The difference between ?

answer :git fetch Just download the changes to the remote repository , Not merged with local branches .

git pull Changes to the remote repository will be downloaded , And merge with the current branch .

git rebase and git merge The difference between ?

answer :git merge and git rebase Are used for branch merging , The key is commit The processing of records is different .

git merge A new one will be created commit object , And then two branches of the previous one commit The records point to this new commit Record . This method will Keep the commit history .

git rebase We'll find the first common of the two branches commit Ancestral records , Then it will extract all of the following from the current branch commit Record , then Put this commit The record is added after the latest commit of the target branch . After this merger , After merging two branches commit Records become linear records Recorded .

 

 

 

Algorithm interview questions

JavaScript How to find the maximum and minimum value of an array ?

answer :

    var arr = [6, 4, 1, 8, 2, 11, 23];
    console.log(Math.max.apply(null, arr))

How to find the most frequently used words in an English article ?

answer :

    function findMostWord(article) {
    //  Legitimacy judgment 
    if (!article) return;
    //  Processing parameters 
    article = article.trim().toLowerCase();
    let wordList = article.match(/[a-z]+/g),
      visited = [],
      maxNum = 0,
      maxWord = "";
    article = " " + wordList.join("  ") + " ";
    //  Traverse to determine the number of times a word appears 
    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;
    }

JavaScript Bubble sort ?

answer : The basic idea of bubble sorting is , Make a pairwise comparison of adjacent elements , In the reverse order, the switch is made , such , Each trip will take the smallest or largest element “ floating ” To the top , In the end, it is completely ordered .

Code implementation :

    function bubbleSort(arr) {
        if (!Array.isArray(arr) || arr.length <= 1) return;
        let lastIndex = arr.length - 1;
        while (lastIndex > 0) { //  When the last exchanged element is the first , All of the following are sorted 
            let flag = true, k = lastIndex;
            for (let j = 0; j < k; j++) {
                if (arr[j] > arr[j + 1]) {
                    flag = false;
                  	lastIndex = j; //  Set the location of the last swap element 
                    [arr[j], arr[j+1]] = [arr[j+1], arr[j]];
                }
            }
          	if (flag) break;
        }
    }

There are two ways to optimize bubble sort .

One is the optimization of the outer loop , Whether we can exchange records in the current loop , If there is no exchange , It means that the sequence is already an ordered sequence . So we don't need to do the next outer loop , This can be done directly .

One is the optimization of inner loop , We can record the position of the last element exchange in the current loop , The sequence after this position is the sequence that has been arranged , So There is no need to compare in a cycle .

Bubble sorting after optimization , When the sort sequence is a sorted sequence , For the best 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's a stable sort .

JavaScript Selection sort ?

answer : The basic idea of sorting is to select the smallest data element from the data elements to be sorted ( Or maximum ) As the first element , Until all the elements are finished .

When the algorithm is implemented , Every time the minimum element is determined, the first position will be the current minimum through continuous comparison and exchange , Switching is a time-consuming operation . Actually It's easy for us to see , Before the current minimum element is fully determined , These exchanges are meaningless . We can set a variable min, Every time you compare Array subscripts that store only smaller elements , When the round cycle is over , Then this variable stores the subscript of the current smallest element , At this point, perform the exchange operation .

Code implementation :

    function selectSort(array) {
      let length = array.length;
      //  If it's not an array or the array length is less than or equal to 1, Go straight back to , There's no need to sort  
      if (!Array.isArray(array) || length <= 1) return;
      for (let i = 0; i < length - 1; i++) {
        let minIndex = i; //  Set the minimum element index of the current loop 
        for (let j = i + 1; j < length; j++) {
          //  If the current element is larger than the minimum element index , The minimum element index is updated 
          if (array[minIndex] > array[j]) {
            minIndex = j;
          }
        }
        //  Exchange 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 an array 
    function swap(array, left, right) {
      var temp = array[left];
      array[left] = array[right];
      array[right] = temp;
    }

Choose Sort, whether or not the initial sequence is ordered , The time complexity is zero O(n²).

The average time complexity of sorting is O(n²) , The worst time complexity is O(n²) , The space complexity is O(1) , It's not a stable order .

JavaScript Insertion sort ?

answer : The basic idea of direct insertion sorting is to put a record to be sorted at each step , Insert into a previously ordered sequence , Until all the elements are inserted .

Insert sort core – The idea of playing cards : Just thinking about playing cards , Take one , It doesn't matter where you put it , And then I'll take another one , Smaller than the first , To the left , Continue to pick up , It could be the middle number , Right in the middle …. successively

Code implementation :

    function insertSort(array) {
      let length = array.length;
      //  If it's not an array or the array length is less than or equal to 1, Go straight back to , There's no need to sort  
      if (!Array.isArray(array) || length <= 1) return;
      //  Cycle from  1  Start ,0  The position is the default sorted sequence 
      for (let i = 1; i < length; i++) {
        let temp = array[i]; //  Save the current elements that need to be sorted 
        let j = i;
        //  Compare... In the currently sorted sequence , If it's bigger than the element that needs to be sorted , Move back in turn 
        while (j -1 >= 0 && array[j - 1] > temp) {
          array[j] = array[j - 1];
          j--;
        }
        //  Insert the found position into the element 
        array[j] = temp;
      }
      return array;
    }

When the sort sequence is a sorted sequence , For 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's a stable sort .

JavaScript Shell Sort ?

answer : The basic idea of Hill sort is to group arrays by a certain increment of subscripts , Sort each group using the direct insertion sort algorithm ; As the increments decrease , Each group contains elements More and more vegetables , When the increment is reduced to 1 when , The whole array is divided into just one group , The algorithm terminates .

    function hillSort(array) {
      let length = array.length;
      //  If it's not an array or the array length is less than or equal to 1, Go straight back to , There's no need to sort  
      if (!Array.isArray(array) || length <= 1) return;
      //  The first layer determines the size of the increment , The size of each increment is halved 
      for (let gap = parseInt(length >> 1); gap >= 1; gap = parseInt(gap >> 1)) {
        //  Use insert sort for each group , Equivalent to the 1 Instead of  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;
    }

Hill sort is to take advantage of the insertion sort for the sorted sequence of the best results , When the initial sequence is unordered , Divide the sequence into several small groups for Radix sorting , Because the sorting base is small , The effect of each cardinality sort is better , It's gradually increasing and then increasing , Increase the size of the group , Because every time is based on the last The result of the second ranking , So each time can be regarded as a sequence of basic sorting , So we can maximize the advantages of insertion sort .

In a nutshell , Since there are only a few integers in each group at the beginning , So the sort is quick . Then each group contains more and more integers , But as these numbers become more and more orderly , So the sorting speed is very fast .

The time complexity of Hill sort varies according to the incremental sequence selected , But overall, the time complexity is less than O(n^2) Of .

Insertion sort is a stable sort , But in Hill's ranking , Because the same element may be in different groups , So the position of the elements may change , So the Hill sort is an unstable sort .

The average time complexity of Hill sort is O(nlogn) , The worst time complexity is O(n^s) , The space complexity is O(1) , It's not a stable order .

There is a height of 10 Stairs of steps , Go up and down , Each step can only be up 1 Or 2 Stepped steps . It is required to use the program to find out how many walking methods there are in total ?

answer : The analysis shows that , Let's say we're only one step away from the last step 10 Steps , There are two situations at this time , Because every step is only allowed 1 Grade or 2 Steps , Therefore, from 8 Steps and steps from 9 Nine steps up . So from 0 To 10 The number of steps is equal to the number of steps 0 To 9 The number of steps plus from 0 To 8 Number of steps . By analogy , We can get a recursive relation , Mark the end of recursion 0 To 1 The number of steps taken and from 0 To 2 Number of steps .

    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);
    }

 

 

 

 

 

Comprehensive interview questions

To talk about ⼀ To talk about let And var The difference between ?

answer :

  • let There is no variable promotion for the command , If in let The former envoy ⽤, It will lead to an error
  • If there is a let and const command , It will form a closed system ⽤ Domain
  • Duplicate statements are not allowed , therefore , Parameters cannot be redeclared inside a function

How to use JS Judge ⼀ An array ?

answer :instanceof ⽅ Law

instanceof The operator is ⽤ To test ⼀ Whether an object is in its prototype chain, a property of the prototype constructor

var arr = [];
arr instanceof Array; // true

constructor ⽅ Law

constructor Property returns a reference to the array function that created this object ⽤, Is to return the corresponding structure of the object function

var arr = [];
arr.constructor == Array; //true

The simplest ⽅ Law

This kind of writing , yes jQuery Is making ⽤ Of


    Object.prototype.toString.call(value) == '[object Array]'
    //  benefit ⽤ This ⽅ Law , Can write ⼀ Of return data type ⽅ Law 
    var isType = function (obj) {
    return Object.prototype.toString.call(obj).slice(8,-1);
    }

ES5 newly added ⽅ Law isArray()

var a = new Array(123);
var b = new Date();
console.log(Array.isArray(a)); //true
console.log(Array.isArray(b)); //false

term ⽬ What performance optimizations have you done ?

answer :

  • Reduce HTTP Number of requests
  • Reduce DNS Inquire about
  • send ⽤ CDN
  • Avoid redirects
  • chart ⽚ Lazy loading
  • Reduce DOM Element quantity
  • Reduce DOM operation
  • send ⽤ external JavaScript and CSS
  • Compress JavaScript 、 CSS 、 typeface 、 chart ⽚ etc.
  • Optimize CSS Sprite
  • send ⽤ iconfont
  • Font clipping
  • Multi domain distribution divides content into different domains
  • Try to reduce iframe send ⽤
  • Avoid graphs ⽚ src It's empty
  • Put the style sheet on link in
  • hold JavaScript Put it on the page ⾯ Bottom

Browser cache ?

answer : Browser cache is divided into strong cache and negotiation cache . When a client requests a resource , Get the cached stream The process is as follows

First of all, according to this resource ⼀ some http header Determine if it hits the cache , If hit , And directly from the local Get cache resources , No requests will be made to the server ;

When the strong cache fails to hit , The client sends the request to the server , Server through another ⼀ some request header Verify that the resource hits the negotiation cache , be called http Revalidation , If hit , The server will return the request , but Do not return resources ,⽽ It tells the client to get directly from the cache , After receiving the return, the client will get the information from the cache Source ;

What strong caching and negotiation caching have in common is , If hit cache , The server does not return resources ; The difference is that , Strong and slow Send the request to the server , But the negotiation cache will .

When the negotiation cache also fails , The server will send the resource back to the client .

When ctrl+f5 When forcing a page refresh , Load directly from the server , Skip strong cache and negotiate cache ;

When f5 When you refresh the page , Skip strong cache , But the negotiation cache will be checked ;

Strong cache

Expires ( The field is http1.0 The norm of time , The value is ⼀ It's an absolute time GMT The time character of the format strand , Represents the expiration time of the cache resource )

Cache-Control:max-age ( The field is http1.1 The specification of , Strong cache profit ⽤ Its max-age It's worth it Determine the maximum value of cache resources ⼤⽣ Life cycle , Its value is in seconds )

Negotiate the cache

Last-Modified ( Value is the last update time of the resource , With the server response return )

If-Modified-Since ( adopt ⽐ Compare two times to judge whether the resource has been modified during the two requests , Such as If there is no modification , Cache negotiation hits )

ETag ( The only way to represent the content of a resource ⼀ identification , With the server response return )

If-None-Match ( Server pass ⽐ More than asking for the head If-None-Match With current resources ETag yes no ⼀ To determine whether a resource has been modified between two requests , If not modified , Cache negotiation hits

What should the front end pay attention to SEO?

answer :

  • reasonable title 、 description 、 keywords : Search for the weight of the three items one by one ⼩, title
  • Emphasize the key points , Important keywords should not appear more than 2 Time ,⽽ And it's up to the front , Different ⻚⾯ title There must be something wrong
  • Same as ; description hold ⻚⾯ Content ⾼ To sum up ,⻓ The degree is right , Don't pile up key words too much , Different ⻚⾯
  • description Somewhat different ; keywords List the key words
  • Semantically HTML Code , accord with W3C standard : Semantic code makes it easy for search engines to understand ⽹⻚
  • Important content HTML Code at the top : Search engine grabs HTML The order is from top to bottom , Some search engines catch up with each other
  • take ⻓ There is a limit to the degree , Make sure the important content ⼀ It's bound to get caught
  • Important content don't ⽤ js Output : climb ⾍ Don't hold on to ⾏js Get content
  • Less ⽤ iframe : Search engines don't grab iframe The content in
  • ⾮ Decorative pictures ⽚ Must be added alt
  • carry ⾼⽹ Standing speed :⽹ Station speed is the search engine ranking ⼀ An important indicator

Browser rendering principle ?

answer :1. Browser received HTML ⽂ And convert it to DOM Trees

When we open ⼀ individual ⽹⻚ when , Browsers will ask for the corresponding HTML ⽂ Pieces of . Although I usually When we write code, they are divided into JS 、 CSS 、 HTML ⽂ Pieces of , That's string , But computers Hardware doesn't understand these strings , So in ⽹ The content transmitted in the network is actually 0 and 1 These bytes of data . After the browser receives the bytes of data , It will convert these bytes of data into character string , That's the code we wrote .

When the data is converted to a string , The browser will first convert these strings into tags through lexical analysis ( token ), this ⼀ Process in lexical analysis is called tokenization ( tokenization )

So what are the markers ? This is actually the compiler principle ⼀ The content of the block . Simply speaking , The mark also Is string , Is the most important component of the code ⼩ Company . this ⼀ The process splits the code into ⼀ Block , And give this Some content is marked , Easy to understand ⼩ What does the unit code mean

When the end of tagging , These tags are then converted to Node , Finally these Node Will be based on Different Node Previous links were constructed as ⼀ star DOM Trees

That's what browsers do from ⽹ I have received HTML ⽂ And then ⼀ Conversion process of series Of course , In parsing HTML ⽂ When it comes to , The browser will also encounter CSS and JS ⽂ Pieces of , At this time Wait for the browser to download and parse these ⽂ Pieces of , Next, let's learn how to use browsers to solve Analysis CSS ⽂ Pieces of

2. take CSS ⽂ Pieces are converted to CSSOM Trees

In fact, conversion CSS To CSSOM The process of trees and up ⼀⼩ The process of the festival is very similar

Here ⼀ In the process , The browser will determine each ⼀ What is the style of each node , And this ⼀ The process is actually very complicated Resource intensive . Because of the style you can ⾃⾏ Set to a node , It can also be obtained by inheritance . Here ⼀ In the process , Browsers have to recurse CSSOM Trees , Then determine what the specific elements look like .

If you're a little confused about why resources are consumed , I this ⾥ For example ⼦

<div>
<a> <span></span> </a>
</div>
<style>
span {
color: red;
}
div > a > span {
color: red;
}
</style>

For the first ⼀ It's a set of styles ⽅ In other words , The browser just needs to find ⻚⾯ All of the span mark Sign and set the face ⾊, But for the first ⼆ It's a set of styles ⽅ In other words , browser ⾸ First we need to find be-all span label , And then find span On the label a label , Finally, I'll find div label , Then give to those who meet this condition span Label setting color ⾊, This recursive process It's complicated . So we should try our best to avoid writing too specific CSS Selectors , And then to HTML Add as little as possible ⽆ Meaning tag , Make sure the levels are flat

3. ⽣ Into a rendering tree

When we ⽣ become DOM Trees and CSSOM After the tree , You need to combine these two trees into a render tree

Here ⼀ In the process , It's not just a combination of the two ⾏ 了 . The rendering tree will only include the nodes that need to be displayed and these sections Dot style information , If a node is display: none Of , Then it won't show up in the render tree .

When browser ⽣ After the rendering tree , It will be based on the rendering tree ⾏ Layout ( It can also be called reflux ), Then tune up ⽤ GPU draw , Composite layer , It's on the screen . For this ⼀ Part of the content is too low-level , It's also about hard This is a piece of related knowledge , this ⾥ It's not going to go on .

21.2 Why to operate DOM slow

presumably ⼤ I've heard the operation at home DOM Poor performance , But what's the reason for this ?

because DOM It belongs to the East rendering engine ⻄,⽽ JS ⼜ yes JS East of the engine ⻄. When we go through JS operation DOM When , Actually, this operation involves communication between two threads , So it's bound to bring ⼀ Some sex Energy loss . operation DOM frequency ⼀ many , Which is the same thing as ⼀ Straight ahead ⾏ Communication between threads , And the operating DOM There may also be a case of redraw backflow , So that leads to performance problems .

classic ⾯ test questions : insert ⼊⼏ m DOM, How to achieve ⻚⾯ No, carton ?

For this question ⽬ Come on ,⾸ We certainly can't ⼀ Second sex ⼏ m DOM Insert it all ⼊, This is bound to cause Carton , Therefore, the key to solve the problem should be how to batch partial rendering DOM .⼤ part ⼈ You can think of it too requestAnimationFrame Of ⽅ I'm going to loop the plug ⼊ DOM , In fact, there is another kind of ⽅ To solve this question topic : Virtual scrolling ( virtualized scroller ).

The principle of this technique is to render only the content in the visible area ,⾮ can ⻅ The region is not rendered at all , When ⽤ Household Replace the rendered content in real time while scrolling

From the picture above, we can see that , Even if the list is ⻓, But the rendering DOM There are only elements forever ⼏ individual , When we roll ⻚⾯ When it's time to update DOM , This technology can solve this problem smoothly This classic ⾯ test questions

21.3 What's blocking rendering

⾸ The premise of rendering first is ⽣ Into a rendering tree , therefore HTML and CSS Definitely blocks rendering . If you want to render more fast , The more you should lower ⼀ Start rendering ⽂ Pieces of ⼤⼩, And flat layers , Optimization selector .

And then when the browser resolves to script When labeling , The build will be suspended DOM , It's only when it's done that it starts from the place where it's suspended ⽅ heavy New start . in other words , If you want to ⾸ The faster the screen is rendered , The less you should be in ⾸ The screen loads JS ⽂ Pieces of , This too It's going to be advice script The label on the body The reason for the bottom of the label .

Now of course , Is not to say that script The label must be at the bottom , Because you can give script add defer perhaps async attribute .

When script Tag plus defer Attribute after , It means that we should JS ⽂ It will and ⾏ download , But it will be put in HTML After parsing, execute in sequence ⾏, So in this case, you can put script The label is placed anywhere .

There is no dependence on JS ⽂ You can add async attribute , Express JS ⽂ Download and parse will not block Put on the rendering .

21.4 Repaint (Repaint) And backflow (Reflow)

Redraw and backflow occur frequently when we set the node style , At the same time, it will be very ⼤ To the extent that it affects can .

  • Redrawing is when a node needs to change its appearance ⽽ It won't affect the layout ,⽐ Such as change color It's called redrawing
  • Reflow is layout or ⼏ What properties need to be changed is called backflow .
  • The return flow is bound to be ⽣ Repaint , Redraw No ⼀ It's bound to cause a backflow . Cost of return ⽐ Repaint ⾼ More , change ⽗ node ⾥ Of ⼦ Nodes are likely to cause ⽗ Node ⼀ Series reflow .

following ⼏ An action can cause performance problems :

  • change window ⼤⼩
  • Change the font
  • Add or remove styles
  • ⽂ Words change
  • Positioning or floating
  • The box model

And a lot of ⼈ I don't know , Redrawing and reflow are actually the same Eventloop of .

  • When Eventloop Of board ⾏ End Microtasks after , Will judge document Need to update , Because the browser is 60Hz The refresh rate of , Every time 16.6ms Will update ⼀ Time .
  • Then judge whether there is resize perhaps scroll event , Some will trigger events , therefore resize and scroll Events are also ⾄ Less 16ms Will trigger ⼀ Time , also ⾃ With throttling function .
  • Judge whether or not it triggers media query
  • Update animation and send events
  • Determine if there is a full screen operation event
  • Of board ⾏ requestAnimationFrame Callback
  • Of board ⾏ IntersectionObserver Callback , The ⽅ Law ⽤ To determine whether the element can ⻅, Sure ⽤ On lazy loading , But the compatibility is not good The renewal world ⾯
  • That's all ⼀ What might be done in the frame . If in ⼀ There is idle time in the frame , They will hold on to ⾏requestIdleCallback Callback

21.5 Reduce redrawing and reflow

  1. send ⽤ transform replace top

<div class="test"></div>
<style>
.test {
position: absolute;
top: 10px;
width: 100px;
height: 100px;
background: red;
}
</style>
<script>
setTimeout(() => {
//  Cause reflux 
document.querySelector('.test').style.top = '100px'
}, 1000)
</script>
  1. send ⽤ visibility Replace display: none , Because the former only causes a redraw , The latter causes backflow ( Changed the layout )

  2. Don't put the attribute value of a node in ⼀ Cycle ⾥ As a cycle ⾥ The variable of

    
        for(let i = 0; i < 1000; i++) {
        //  obtain  offsetTop  Can cause reflux , Because you need to get the right value 
        console.log(document.querySelector('.test').style.offsetTop)
        }
  3. Don't make ⽤ table Layout , It could be very ⼩ Of ⼀ individual ⼩ The change will cause the whole thing table relayout

  4. Animation to achieve the speed of the choice , The faster the animation , The more reflux , You can also choose to make ⽤requestAnimationFrame

  5. CSS The selector matches from right to left , Avoid excessive node hierarchy

  6. Set nodes that are frequently redrawn or backdrawn to layers , Layers can block ⽌ Rendering of this node ⾏ To affect other nodes .⽐ As for the video The label is , Browser meeting ⾃ Turn the node into a layer .

Set node to layer's ⽅ There are a lot of , We can go through the following ⼏ A regular ⽤ Attributes can ⽣ Make a new layer

will-change

video 、 iframe label

⼀ A page ⾯ There are ⼤ The graph of quantity ⽚(⼤ E-commerce ⽹ standing ), Slow load , What do you have some ⽅ To optimize these graphs ⽚ Loading , to ⽤ A better experience .

answer :

  • chart ⽚ Lazy loading , On the page ⾯ Invisible areas on can be added ⼀ A rolling event , Judgment diagram ⽚ The distance between the location and the top of the browser and the page ⾯ Distance of , If the former ⼩ In the latter , Priority load .
  • If it's a slide show ⽚、 Album, etc , You can make ⽤ chart ⽚ Preloading technology , The current display ⽚ Before ⼀ Zhang and hou ⼀ Download first .
  • If the figure ⽚ by css chart ⽚, You can make ⽤ CSSsprite , SVGsprite , Iconfont 、 Base64 Technology .
  • If the figure ⽚ too ⼤, You can make ⽤ Specially coded graphs ⽚, It will be loaded first ⼀ A very compressed thumbnail , To mention ⾼⽤ User experience .
  • If the figure ⽚ Display area ⼩ In the picture ⽚ The real ⼤⼩, Because on the server side, according to the business needs first ⾏ Into the ⾏ chart ⽚ Compress , chart ⽚ After the compression ⼤⼩ And show ⼀ Cause .

The webpage verification code is ⼲ Well , It's to solve some security problems ?

answer :

  • distinguish ⽤ Is it a computer or a computer ⼈ The public whole of ⾃ Move the program . It can prevent ⽌ Malicious password cracking 、 Brush ticket 、 The forum is full of ⽔
  • Effectively prevent ⽌⿊ Guest to... Etc ⼀ Specific registrations ⽤ Household ⽤ Specific programs ⼒ Crack ⽅ Step in ⾏ Keep trying to land

 

My favorite interviewers

  • A solid
    • From years of experience , Those students with good development have solid basic knowledge
    • For example, only understand jQuery Don't understand, JavaScript No way
    • It would be better to know the basics of computers , Because we're going to have a lot of problems with non front end technologies
  • Think actively
    • Students who finish tasks passively will make slow progress here
    • You need to have your own ideas , Instead of just finishing the task
  • like to study
    • The front-end domain knowledge is quickly eliminated , So it's better to learn and get in touch with new things often
  • There is depth
    • When encountering problems, study the deep reasons behind it , Instead of trying to get around first
    • Like tracking down something Bug The reason why we always understand its nature
  • There's a vision
    • Innovation often comes from the intersection of different disciplines , If you know more about the field , The more likely you are to have new ideas

All right. , So much for the front-end interview , See you next time ! Finally, I wish you all the best offer!

版权声明
本文为[osc_ ohsup7nf]所创,转载请带上原文链接,感谢
https://cdmana.com/2020/12/20201225095044696o.html

Scroll to Top