Front-end development interview questions
Site address:Full stack development
Original link:Front-end development interview questions
HTML
- Doctype effect? What are the differences between standard mode and compatible mode?
1、
<! DOCTYPE>
The declaration is located on the first line in the HTML document, at<html>
Before labeling, tell the browser’s parser what document standard to parse with. The absence or incorrect format of DOCTYPE will cause the document to be rendered in compatible mode.
2. The typesetting of the standard mode and JS operation mode are both running at the highest standard supported by the browser. In compatibility mode, the page is displayed in a relaxed backward compatible manner, simulating the behavior of old browsers to prevent the site from failing to work.
- Why does HTML5 only need to be written
<! DOCTYPE HTML>
?
HTML5 is not based on SGML (standard generalized markup language), so there is no need to reference DTD (document type definition), but
doctype
To regulate the behavior of browsers (let browsers run as they should)
HTML4.01 is based on SGML, so you need to refer to DTD to inform the browser of the document type used by the document.
- What are the in-line elements? What are the block-level elements? Empty (
void
What are the elements?
First of all, the CSS specification stipulates that each element has
display
Property to determine the type of calcium element, each element has a defaultdisplay
Values such asdiv
Thedisplay
The default value isblock
, are all block-level elements;span
Defaultdisplay
Attribute value isinline
, is an inline element.
1. In-line elements:a
、b
、span
、img
、input
、select
、strong
(accent)
2. Block level elements:div
、ul
、ol
、li
、dl
、dt
、dd
、h1
、h2
、h3
、h4
、p
3. Common Empty Elements:br
、hr
、img
、input
、link
、meta
Unusual empty elements:area
、base
、col
、command
、embed
、keygen
、param
、source
、track
、wbr
- When importing styles from a page, use the
link
And@import
What’s the difference?
1、
link
belong toXHTML
Label, except loadCSS
In addition, it can also be used to defineRSS
, definitionrel
Connection properties, etc. And@import
YesCSS
Provided, can only be used for loadingCSS
.
2. When the page is loaded,link
At the same time is loaded, and@import
ReferencedCSS
Will wait until the page is loaded before loading.
3、import
YesCSS2.1
The proposal was made only inIE5
The above can be identified, andlink
YesXHTML
Label, no compatibility problem.
4、link
Support for useJS
ControlDOM
Change the style while@import
Not supported.
- What is your understanding of the browser kernel?
It is mainly divided into two parts: rendering engine (
layout
Orengine
) and JS engine.
Rendering engine: responsible for obtaining the contents of the webpage (HTML, XML, images, etc.), organizing the information (adding CSS, etc.), and calculating the display mode of the webpage, and then outputting to the display or printer. Different browsers have different interpretations of the syntax of web pages, so the rendering effect is also different. All web browsers, e-mail clients, and other applications that need to edit and display network content need a kernel.
JS Engine: Parses and executes JS to achieve dynamic effects of web pages.
At first, there was no clear distinction between rendering engine and JS engine. Later, as JS engines became more and more independent, kernel tended to refer to rendering engine only.
- What are the common browser kernels?
Trident
Kernel: IE, MaxThon, TT, The World, 360, Sogou Browser, etc [MSHTML]Gecko
Kernel: Netscape6 and above, FF, Mozilla Suite/SeamKey, etc.Presto
Kernel: Opera7 and above [Opera kernel was:Presto
, now:Blink
]Webkit
Kernel: Safari, Chrome, etc [Chrome: Blink (Branch of WebKit)]
- What are the new features and removed elements of HTML5? How to handle the browser compatibility problem of HTML5 new tags? How to distinguish HTML from HTML5?
HTML5 is no longer a subset of SGML. it is mainly about the increase of image, location, storage, multitasking and other functions.
Paintingcanvas
For media playbackvideo
Andaudio
Element
Local offline storagelocalStorage
Long-term storage of data, data will not be lost after the browser is closed.sessionStorage
The data of is automatically deleted after the browser is closedBetter semantic content elements, such as
article
、footer
、header
、nav
、section
Form controls:calendar
、date
、time
、url
、search
New technologies:webworker
、websocket
、Geolocation
Elements removed:
Elements of pure expression:basefont
、big
、center
、font
、s
、strike
、tt
、u
Elements that have a negative impact on usability:frame
、frameset
、noframes
Support HTML5 new tags:
IE8/IE7/IE6
Support adoptiondocument.createElement
The tags generated by the method can use this feature to enable these browsers to support HTML5 new tags. after the browsers support the new tags, they also need to add default styles.
You can also use mature frameworks directly, such ashtml5shim
:
<!--[if lt IE 9]>
<script> src="http://html5shim.googlecode.com/svn/trunk/html5.js"</script>
<![endif]>
Distinguish HTML5,:DOCTYPE declaration, new structural elements, functional elements, etc
- Briefly describe your understanding of HTML semantics?
Semanticization makes the content of the page structured and clearer, which is convenient to analyze browsers and search engines.
You can read documents without CSS styles.
Search engine crawlers rely on HTML tags to determine the context and weight of each keyword, which is conducive to SEO
- How to use the offline storage of HTML5 and explain the working principle?
When users are not connected to the Internet, they can normally access sites or applications; In the case of networking, update the cache file on the user’s machine.
Principle: The offline storage of HTML5 is based on a newly built.appchache
The caching mechanism of files (not storage technology) stores resources offline through the parsing list on this file, and these resources will look likecookie
The same is stored. After that, when the network is offline, the browser will display the page through the data stored offline.How to use:
1, add a page headermanifest
Property of
2. Incache.manifest
The compilation of files is an offline storage resource.
3, in the offline state, operationwindow.applicationCache
Implementation of requirements
- How does the browser manage and load the offline storage resources of HTML5?
While online, the browser found that
html
The head hasmanifest
Property, which requests themanifest
File, if it is the first visitapp
, the browser based onmanifest
The contents of the file download the corresponding resources and are stored offline.
If you have already visitedapp
, and the resources have been stored offline, the browser will use the offline resources to load the page, and then the browser will compare the newmanifest
File, if the file has not changed, no action will be taken, otherwise the resources in the file will be downloaded again and stored offline.
When offline, the browser directly uses the resources stored offline.
- Please describe
cookie
,sessionStorage
,localStorage
The difference?
cookie
Is the data (usually encrypted) stored on the user’s local terminal by the website in order to identify the user’s identitycookie
The data are always homologoushttp
The request is carried (even if not required) and will be passed back and forth between the browser and the server.sessionStorage
AndlocalStorage
The data will not be automatically sent to the server and will only be saved locally.Storage size:
cookie
Data size cannot exceed4k
sessionStorage
AndlocalStorage
Although there is also a storage size limit, but thancookie
It is much larger and can be achieved5M
Or greaterValid time:
localStorage
Persistent data is stored and will not be lost after the browser is closed unless the data is actively deleted.sessionStorage
Data is automatically deleted after the current browser window is closed.cookie
Setcookie
Valid until expiration time, even if window or browser is closed.
-
iframe
What are the disadvantages?
iframe
It will block the main pageonload
Events
The search engine’s search program cannot interpret such pages, which is not conducive to SEO.iframe
And the browser has restrictions on the connections of the same domain, thus affecting the parallel loading of pages
Useiframe
Two shortcomings need to be considered before. If you need to useiframe
, preferably through JS
Dynamic givingiframe
Addsrc
Attribute value, can bypass the above two problems.
-
label
What is its function? How?
label
Labels define the relationship between form controls. When the user selects the label, the browser will automatically turn the focus to the form controls related to the label.
<label for="Name">Number:</label>
<input type="text" name="Name" id="Name">
- HTML5
form
How do I turn off the auto-completion function?
For those who don’t want to be prompted
form
Or someinput
Set toautocomplete=off
- How to realize the communication between multiple tabs in the browser? (Ali)
WebSocket
,SharedWorkder
You can also calllocalStorage
、cookies
Such as local storage methodslocalStorage
When another browsing context is added, modified or deleted, it will trigger an event to communicate page information by monitoring the event and controlling its value
-
WebSocket
How to Compatible with Low Browsers? (Ali)
Adobe Flash Socket
ActiveX HTMLFile(IE)
Based onmultipart
Coded transmissionXHR
Based on long pollingXHR
- What can page visibility do?
via
visibilityState
The value of detects whether the page is currently visible and when the page is opened.
When the page is switched to other background processes, the playing of music or video is automatically suspended
- How to realize a circular clickable area on the page?
1、
map+area
Or ..SVG
2、border-radius
3. pure JS implementation requires a simple algorithm where a point is not on a circle, obtaining mouse coordinates, etc
- Implementation Not Used
border
Draw1px
The high line can maintain the same effect under the standard mode and weird mode of different browsers.
<div style="height: 1px;overflow: hidden;background: red;"></div>
<div style=”height: 1px; overflow: hidden; background: red;” ></div>
CSS
- What about the box model of standard CSS? What is the difference between the box model of the lower version IE?
1, there are two kinds, IE box model, W3C box model
2. Box Model: Content (content
), fill (padding
), boundary (margin
), borders (border
)
3. Difference: IE’scontent
Part handleborder
Andpadding
Count in
- What are the CSS selectors? Which attributes can be inherited?
1. ID selector
2. Class Selector
3. Label Selector
4. Adjacent Selectors (h1+p
)
5. Sub-selectors (ul>li
)
6. Descendant Selector (li a
)
7. Wildcard Selector (*
)
8. Attribute Selector (a[rel="external"]
)
9, pseudo class selector (a:hover,li:nth-child
)Inheritable styles:
font-size
、font-family
、color
、ul
、li
、dl
、dd
、dt
Non-inheritable styles:border
、padding
、margin
、width
、height
- How is CSS priority calculated?
The principle of nearest priority shall prevail over the nearest style definition under the same weight.
The loading style is based on the last loaded location.Priority is:
Same weight: inline style sheet (inside label) > embedded style sheet (current file) > external style sheet (external file)! important > id > class > tag
! important
Higher priority than inline
- What are the new pseudo classes in CSS3?
p:first-of-type
Select the first element belonging to its parent<p>
Elementp:last-of-type
Select the last element belonging to its parent<p>
Elementp:only-of-type
Select the unique that belongs to its parent element<p>
Elementp:nth-child(2)
Select each of the second child elements belonging to its parent element<p>
Element::after
Adding content before an element can also be used to clear the float.::before
Add content after element::enabled ::disabled
Controls the disabled state of form controls:checked
The radio box or check box is selected
- Horizontal center: here
div
Set a width and addmargin: 0 auto
Attribute
div {
width: 200px;
margin: 0 auto;
}
- Let the absolute positioning
div
Center
div {
position: absolute;
width: 200px;
height: 200px;
margin: auto;
left: 0;
top: 0;
right: 0;
bottom: 0;
background: #ccc;
}
- Horizontal vertical center one
Determine the width and height of the container
Sets the outer edge distance of the layer
div {
position: absolute;
width: 200px;
height: 200px;
left: 50%;
top: 50%;
margin: -100px 0 0 -100px;
background: #ccc;
}
- Horizontal vertical center 2
Unknown container width and height, using
transform
Attribute
div {
position: absolute;
width: 200px;
height: 200px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: #bbb;
}
- Horizontal vertical center three
utilize
flex
Layout
Compatibility should be considered in actual use.
body {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
div {
display: flex;
align-items: center;
justify-content: center;
width: 300px;
height: 300px;
background: green;
}
span {
width: 100px;
height: 100px;
background-color: #ccc;
}
-
display
What are the values? Explain their role?
block
Block type. The default width is the width of the parent element. You can set the width and height to display line breaks.none
The default value. Displays as in-line element types.inline
In-line element type. The default width is the content width, and the width and height cannot be set. It is displayed by peers.inline-block
The default width and height is the content width. You can set the width and height for peer display.list-item
Display like a block type element and add style list tags.table
This element is displayed as a block-level table.inherit
Provisions should be inherited from the parent elementdisplay
The value of the property.
-
position
The value ofrelative
Andabsolute
Positioning the origin?
absolute
Generates an absolutely positioned element that is not relative to the valuestatic
To locate the first parent element of thefixed
(Not Supported by Old IE) Generates absolutely positioned elements that are positioned relative to browser windowsrelative
Generating relatively positioned elements and positioning relative to their normal positionsstatic
Default value. No positioning, element appears in normal stream (ignoredtop
、right
、bottom
、left
Statement)inherit
Specifies inheritance from the parent elementposition
The value of the property
- What are the new features of CSS3?
Add various CSS selectors (
:not(.input)
): Allclass
Noinput
The node of
Rounded cornerborder-radius:8px;
Multi-column layoutmulti-column layout
Shadow reflectionsshadow\reflect
Text effectstext-shadow
Text renderingtext-decoration
Linear gradientgradient
Rotationtransform
Zoom, Position, Tilt, Animation, Multi-Background
For example:transform:\scale(0.85,0.90)\translate(0,-30px)\skew(-9deg,0)\animation
- Please explain CSS3
flexbox
(Elastic Box Layout Model) and Applicable Scenarios?
A new CSS3 function for page layout,
flexbox
You can put the list in the same direction (top to bottom, left to right) and allow the list to extend to occupy available space.
More complex layouts can also be implemented by nesting a telescoping container (flex container
) to achieve.
Useflex
Elements of the layout, calledflex
Container (flex container
), short forcontainer
All its child elements are automatically called container members and are calledflex
Project (flex item
), short forProjects
The conventional layout is based on block and inline flow directions, whileflex
The layout is based onflex-flow
Stream can be easily used for centering and can adapt to different screen sizes.
- What is the principle of creating a triangle with pure CSS?
Hide the top, left and right sides (color set to
transparent
)
div {
width: 0;
height: 0;
border: 100px solid;
border-color: transparent transparent red transparent;
}
- How to Design a Full Screen
Products
Word layout?
Simple way:
Abovediv
Wide100%
The following twodiv
Separate width50%
Then usefloat
Or ..inline
Just make it not wrap
body {
margin: 0;
padding: 0;
}
.header {
width: 100%;
height: 300px;
background: green;
}
.left {
width: 50%;
height: 300px;
background: aqua;
float: left;
}
.right {
width: 50%;
height: 300px;
background: blue;
float: right;
}
- How to Realize CSS Multi-column Contour?
utilize
padding-bottom|margin-bottom
Positive and negative values offset;
Set parent container out of hidingoverflow:hidden;
In this way, the height of the parent container or the row inside it is not setpadding-bottom
When the height;
When the height of any column in it increases, the height of the parent container is expanded to the height of the highest column in it
Others lower than this will use them.padding-bottom
Compensate the height difference of this part.
body {
padding: 0;
margin: 0;
}
.container {
width: 100%;
height: 300px;
overflow: hidden;
}
.left {
float: left;
width: 30%;
height: 100px;
background: aqua;
padding-bottom: 200px;
margin-bottom: -200px;
}
.right {
float: right;
width: 70%;
height: 200px;
background: #6cc;
padding-bottom: 200px;
margin-bottom: -200px;
}
- What are the compatibility of browsers you often encounter? Why, what is the solution? Hack skills commonly used?
png24
Bits of pictures appear in the background on IE6 browser, the solution is to make itpng8
Browser defaultmargin
Andpadding
Different. The solution is to add a global{margin:0; padding:0; }
To unify
IE6 Bilateral Distancebug
Block attribute labelfloat
After that, there was another rampagemargin
In case, it is displayed in IE6margin
Larger than set
Double distance generated by floating IE
#box {
float: left;
width: 10px;
margin: 0 0 0 100px;
}
IE will be generated in this case.
20px
The distance, the solution is infloat
Add to the label style control of_display:inline;
Convert it into an inline attribute. (_
This symbol is only recognized by IE6)
The method of gradual identification gradually excludes parts from the whole.
First of all, skillfully use\9
This tag separates IE browser from all cases.
Then, use it again.+
Separate IE8 from IE7 and IE6 so that IE8 has been independently identified.
div {
background-color: red; /*所有识别*/
background-color: #00deff \9; /*IE6、7、9识别*/
_background-color: #1e0bd1; /*IE6识别*/
}
Under IE, you can use the method of obtaining general attributes to obtain custom attributes, or you can use
getAttribute()
Get custom attributes;
Only available under firefoxgetAttribute()
Get custom properties
Solution: Uniform AdoptiongetAttribute()
Get custom propertiesIE
event
The objects arex
、y
Property, but nopageX
、pageY
Attributes;
Under Firefoxevent
The objects arepageX
、pageY
Property, but nox
、y
Attribute
Solution: (conditional comments) The disadvantage is that additional HTTP requests may be added under IE browser.Chrome Chinese will default to less than
12px
According to the text of the mandatory12px
display
By adding CSS properties-webkit-text-size-adjust:none;
SolveAfter hyperlink access
hover
The style does not appear, and the clicked hyperlink style no longer hashover
Andavtive
.
Solution: Change the order of CSS attributes.
L-V-H-A:a:link{} a:visited{} a:hover{} a:active{}
-
li
Andli
What causes the invisible gap between them? What is the solution?
The arrangement of line boxes will be affected by the middle spaces (carriage return/spaces), etc. because spaces are also characters, these spaces will also be applied with styles and occupy space, so there will be intervals, and the character size will be set to
0
, there is no space.
- Why do you want to initialize CSS styles?
Browsers have compatibility problems. Different browsers have different default values for some tags. Without CSS initialization, there will be page display differences between browsers.
Initialization style will have certain influence on SEO, and initialization will be carried out as far as possible under the condition of minimum influence.
-
absolute
Thecontaining block
(Container Block) How is the calculation different from normal flow?
No matter which kind it belongs to, the nearest of its ancestor elements must be found first.
position
The value is notstatic
Element, and then judge:
1. If this element isinline
Element, thencontaining block
The first and last generated to be able to contain this elementinline box
Thepadding box
(exceptmargin
,border
The outer region) of the image.
2, otherwise by this ancestor elementpadding box
constitute
If none is found; otherwiseinitial containing block
Add:
1、static/relative
, its parent element’s content box (i.e. removedpadding
Part of)
2、absolute
: Find Up The nearest location isabsolute、relative
Elements of
3、fixed
: it’scontaining block
Is always the root element (html/body
), the root element is alsoinitial containing block
- CSS
visibility
Property hascollapse
What is the function of attribute value? What is the difference between different browsers?
For common elements
visibility:collapse;
The element is completely hidden and does not occupy the page layout space, anddisplay:none;
The performance is the same. If the target element istable
,visibility:collapse;
willtable
Hidden, but will occupy the page layout space. Only works under Firefox, IE will display elements, Chrome will hide elements but occupy space.
-
position
withdisplay
、margin collapse
、overflow
、float
What happens when these characteristics are superimposed on each other?
If the of the element
display
Fornone
, then the element is not rendered,position
,float
Does not work;
If the element hasposition:absolute;
Orposition":fixed;
Attribute, the element will be absolutely positioned,float
It doesn’t work.
If the elementfloat
Attribute is notnone
, the element leaves the document stream, depending on thefloat
Property value. There are floating, absolute positioning,inline-block
The element of the attribute,margin
Not with other elements in the vertical directionmargin
Fold.
- What is the understanding of BFC specification (block level formatting context)?
It is an independent container, which determines how an element locates its content and its relationship and interaction with other elements.
A page is made up of multiple boxes, the types of elements anddisplay
Property determines the type of this Box
Different types of Box will participate in differentFormatting Context
(Determines how the container of the document is rendered), so the elements in the Box will be rendered in different ways, that is, elements inside the BFC and elements outside the BFC will not affect each other.
- CSS defined weights
Rule of Weight: The weight of the label is
1
,class
The weight of is10
,id
The weight of is100
.
- Please explain why it is necessary to clear the float. How to clear the float?
Clear Floating is to clear the effects of using floating elements.
For floating elements, the height will collapse, while the height collapse will make the layout behind our page unable to display normally.1. Parent
div
Definitionheight
;
2. Parentdiv
Also floating together;
3, the conventional use of a.class
;
.clearfix:before, .clearfix:after {
content: '';
display: table;
}
.clearfix:after {
clear: both;
}
.clearfix {
*zoom: 1;
}
When SASS is compiled, the parent of the floating element
div
Defining Pseudo Classes:after
div:after, div:before {
content: '';
visibility: hidden;
display: block;
height: 0;
clear: both;
}
Analytical principle:
1、displa:block;
The generated elements are displayed as block-level elements to occupy the remaining space;
2、height:0
The height of the original layout is prevented from being damaged by generated content;
3、visibility:hidden;
Make the generated content invisible and allow content that may be covered by the generated content to be clicked and interacted;
4. Adoptioncontent:"."
The generate content is taken as that last element,
5、zoom:1;
Trigger IEhasLayout
According to the analysis, besidesclear:both
Used to close floating, other code is to hidecontent
The content generated, which is why other versions of closed floating havefont-size:0
,line-height:0
- What is outside distance merger?
Outside distance merging means that when two vertical outside distances meet, they will form an outside distance.
The height of the combined outer edge distance is equal to the greater of the heights of the two combined outer edge distances.
-
zoom:1
The principle of cleaning and floating?
Clear float, trigger
hasLayout
;zoom
Property is a proprietary property of IE browser, which can set or retrieve the zoom ratio of the object. Solve the problem of IEbug
For example, the overlap of outer edge distance, floating clearance and IE triggeringhasLayout
Attributes, etcWhen set
zoom
After the value of, the set elements will expand or shrink, the height and width will be recalculated, once changedzoom
Value will also occur when rendering again, using this principle to solve the IE child element floating parent element does not automatically expand with the problem.Currently, non-IE browsers do not support this attribute. You can use the animation attribute in CSS3.
scale
Zoom in and out.
- How does the browser parse the CSS selector?
Match from the key selector, then move left to find the rule selector ancestor element.
As long as the subtree of the selector is working, the style system will continue to move to the left until it matches the rule or abandons the rule because it does not match.
-
margin
Andpadding
What scenarios apply respectively?
margin
Used to separate the spacing between elements;padding
Used to separate elements from content.margin
The separate element used for layout make that elements irrelevant to each other;padding
Used for spacing between elements and content, so that there is a distance between content and elements.
-
::before
And:after
What is the difference between a double colon and a single colon? Explain the role of these two pseudo-classes?
Single colon (
:
) for CSS3 pseudo-classes, double colons (::
) for CSS3 pseudo elements. (Pseudo elements consist of double colons and pseudo elements)
Double colons are introduced in the current specification to distinguish pseudo classes from pseudo elements.
-
How to modify Chrome to automatically fill in the yellow background of the form after remembering the password?
input:-webkit-autofill, textarea:-webkit-autofill, select:-webkit-autofill {
background-color: rgb(250, 250, 189); background-image: none; color: rgb(0, 0, 0);
}
- After the element is set to float, the
display
What is the value?
Become automatically
display:block
- How can Chrome support less than
12px
The words?
1. Use picture: if the content is fixed, the use will be less than
12px
Cut out the text to make pictures, which is both compatible and beautiful.
2. Use12px
Font size style setting, if Chrome is not considered, compatibility can be ignored while setting less than12px
Object settings-webkit-text-adjust:none
To achieve maximum compatibility considerations.
4. Use12px
Above fonts, reconsider compatibility under weight.
- How to use CSS to make the font of the page clear and thin?
-webkit-font-smoothing:antialiased;
-
position:fixed;
What if it is invalid under Android?
fixed
The element of is fixed relative to the whole page, sliding on the screen is just moving this so-calledviewport
It’s not that IOS doesn’t support itfixed
, justfixed
The element of is not fixed relative to the mobile phone screen.
- What is the minimum time interval for manual animation?
The default frequency for most displays is
60Hz
, i.e. 1 second refresh60
Time, so the theoretical minimum interval is1/60*1000ms=16.7ms
-
display:inline-block
When will the gap be displayed?
Remove spaces, use
margin
Negative value, usefont-size:0
、letter-spacing
、word-spacing
- what is
cookie
Isolation? (Do not let a resource carry cookie when requesting it)
If static files are placed under the primary domain name, static files are requested with
cookie
Data submitted toserver
, very waste of traffic.Because ..
cookie
There are domain restrictions, so requests cannot be submitted across domains, so when non-primary domain names are used, they will not be included in the request headercookie
Data.
This can reduce the size of the request header and the request time, thus achieving the purpose of reducing the overall request delay.
At the same time, this method will notcookie
Incoming Web Server also reduces the number of Web Server pairscookie
The processing and analysis link of.
The resolution speed of HTTP requests of the webserver is improved.
JavaScript
- Introduce the basic data types of JS
undefined
、null
、Boolean
、number
、string
ES6 Add:symbol
(Create unique and immutable data types)
- What built-in objects does JS have?
Object
Is the parent of all objects in JS
Data Encapsulation Class Object:Object
、Array
、Boolean
、Number
AndString
Other objects:Function
、arguments
、Math
、Date
、RegExp
、Error
- The Basic Specification for JS Writing
1. Do not declare multiple variables on the same line
2. Use===/! ==
To comparetrue/false
Or a numerical value
3. Use literal substitution of objectsnew Array
4. Do not use global functions
5、switch
Statement must havedefault
branch
6. The function should have a return value
7、for
Loop must use braces
8、if
Statement must use braces
9、for-in
Variables in loops should be usedvar
Keyword clearly limits scope, thus avoiding scope pollution
- JS prototype, prototype chain? What are the characteristics?
Each object initializes an attribute inside it, which is
prototype
(Prototype) When accessing an object’s attribute, if the attribute does not exist inside the object, it will goprototype
Find this attribute, thisprototype
There will be their ownprototype
, so repeatedly, is the concept of prototype chain.Relationships:
instance.constructor.prototype=instance.__proto__
Features:
JS objects are passed by reference, and there is not a prototype copy of each new object entity created. When the prototype is modified, the objects associated with it will also inherit the change.When an attribute is needed, the JS engine will first see if there is this attribute in the current object, and if not, it will look for it.
prototype
Whether the object has this attribute, so recursive, has been retrievedObject
Built-in object.
function Func() {}
Func.prototype.name = "Sean";
Func.prototype.getInfo = function () {
return this.name;
};
var person = new Func();//var person=Object.create(oldObject)
console.log(person.getInfo());//Sean
console.log(Func.prototype);//Object {name: "Sean"}
- JS has several types of values. Draw a memory map?
Stack: Original Data Type (
undefined
,null
、Boolean
、number
、string
)
Heaps: Reference Data Types (Objects, Arrays, and Functions)The difference between the two types: different storage locations
The original data type is a simple data segment stored directly in the stack, which occupies a small space and has a fixed size and belongs to frequently used data, so it is stored in the stack.
Referencing objects whose data types are stored in the heap occupies a large space and is not fixed in size. If stored in the stack, it will affect the performance of the program.
The reference data type stores a pointer in the stack that points to the starting address of the entity in the heap. When the parser looks for the reference value, it first retrieves its address in the stack and obtains the entity from the heap after obtaining the address.
- How to convert a string into a number, for example
12.3b
?
parseFloat('12.3b');
- How to add a comma to the number to the left of floating point number every three bits, such as
12000000.11
Convert to12,000,000.11
?
function commafy(num) {
return num && num.toString().replace(/(\d)(?=(\d{3})+\.)/g, function ($1, $2) {
return $2 + ',';
})
}
- How to realize random sorting of arrays?
//方法一:
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
function randSort(arr) {
for (var i = 0, len = arr.length; i < len; i++) {
var rand = parseInt(Math.random() * len);
var temp = arr[rand];
arr[rand] = arr[i];
arr[i] = temp;
}
return arr;
}
//方法二:
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
function randSort(arr) {
var mixedArray = [];
while (arr.length > 0) {
var randomIndex = parseInt(Math.random() * arr.length);
mixedArray.push(arr[randomIndex]);
arr.splice(randomIndex, 1);
}
return mixedArray;
}
//方法三:
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
arr.sort(function () {
return Math.random() - 0.5;
});
- How does JS implement inheritance?
1. Structure
2. Prototype
3. Examples
4. CopyPrototype
prototype
Mechanism orapply
Andcall
The method is relatively simple to implement, and it is recommended to use a hybrid method of constructor and prototype.
function Parent() {
this.name = name;
}
function Child() {
this.age = age;
}
Child.prototype = new Parent();//继承Parent,通过原型
- How does JS create objects?
JS creates objects by using built-in objects or various custom objects, and can also use
JSON
;
1. Literal Quantity of Objectsvar person={firstname:"Mark",lastname:"Yun"}
2. Usefunction
Simulate parameterless constructors
function Person() {}
var person = new Person();//定义一个function,如果使用new实例化,该function可以看作一个class
person.name = "Mark";
person.age = "25";
person.word = function () {
return person.name + 'hello'
};
3. Use
function
Simulate parameter constructors to implement (withthis
Keyword defines the context attribute of the construct)
function Pet(name, age, hobby) {
this.name = name;//this作用域,当前对象
this.age = age;
this.hobby = hobby;
this.eat = function () {
return "我是" + this.name + ",我喜欢" + this.hobby + ",是个程序员。";
}
}
var maidou = new Pet("麦兜", 25, "coding");//实例化、创建对象
maidou.eat();//调用eat方法
4. Create (built-in object) in factory mode
var mcDog = new Object();
mcDog.name = "旺财";
mcDog.age = 3;
mcDog.work = function () {
return mcDog.name + ',汪汪汪......';
};
mcDog.work();
5. Create by prototype
function Dog() {}
Dog.prototype.name = "旺财";
Dog.prototype.eat = function () {
return this.name = "是个吃货"
};
6. Create it in a mixed way
function Car(name, price) {
this.name = name;
this.price = price;
}
Car.prototype.sell = function () {
return "我是" + this.name + ",我现在卖" + this.price + "万元。";
};
var camry = new Car("凯美瑞", 27);
- JS scope chain?
Global functions cannot view the internal details of local functions, but local functions can view the functional details of their upper layers until they reach global details.
When a certain attribute or method needs to be found from a local function, if the current scope is not found, it will be traced back to the upper scope to find until the global function. This organizational form is scope chain.
- Talk about Yes
this
Understanding of Objects?
this
Always points to the direct caller of the function;
If sonew
Key words,this
point tonew
Out of the object;
In the event,this
Point to the object that triggered this event, especially in IEattachEvent
hit the targetthis
Always point to global objectswindow
.
-
eval
The role of?
Its function is to parse the corresponding string into JS code and run it.
Use should be avoidedeval
, unsafe, very performance intensive (2
Time, once resolved into JS statement, once executed)
ByJSON
String conversion toJSON
You can use theeval
,var obj=eval('('+str+')');
- what is
window
Object? what isdocument
Object?
window
An object is a window opened by a browser.document
Object is a read-only reference to the Document object (HTML document object),window
An attribute of the object.
-
null
、undefined
The difference?
null
Indicates that the value of an object isEmpty;undefined
Indicates that a variable is declared but not initialized (assigned);
undefined
Is not an effectiveJSON
, andnull
Yes;undefined
Type of (typeof
Yesundefined
null
The type oftypeof
Yesobject
JS will default the unassigned variable to
undefined
;
JS never sets the variable tonull
. It is used to indicate a certain purpose.var
Declared variable has no value.
typeof undefined; //undefined
undefined
: is a representationNoThe original value or representation ofMissing valueThat is, there should be a value here, but it has not been defined yet.
typeof null; //null
null
: is an object (empty, without any attributes or methods)
As a parameter of the function, it means that the parameter of the function is not an object;Note:
In verificationnull
When, must use===
Because==
Unable to distinguishnull
Andundefined
null == undefined;//true
null === undefined;//false
Write a generic event listener function
< pdata-height = “565” data-theme-id = “0” data-slug-hash = “bkjvm” data-default-tab = “js” data-user = “whjin” data-embedded-version = “2” data-pen-title = “generic event listener function” class=”codepen”>See the PenCommon Event Listener Functionsby whjin (@whjin) onCodePen.</p>
<script async src=”https://static.codepen.io/ass …; ></script>
-
['1', '2', '3'].map(parseInt);
What is the answer?
['1', '2', '3'].map(parseInt); //[ 1, NaN, NaN ]
;parseInt()
Function can parse a string and return an integer, requiring two arguments (val
、radix
);
among themradix
Represents the cardinality of the number to be resolved. (The value is between2~36
, and the number in the string cannot be greater thanradix
In order to correctly return the numerical result value);
Heremap
Wear3
Of (element,index,array
), rewriteparseInt
Function tests whether the above rules are met.
function parseInt(str, radix) {
return str + '-' + radix;
}
var a = ['1', '2', '3'];
console.log(a.map(parseInt));//[ '1-0', '2-1', '3-2' ]不能大于radix
Because there are no numbers in the binary
3
, resulting in an out-of-rangeradix
Assignment and illegal binary parsing will only be returnedNaN
.
- What is an event? What is the difference between IE and Firefox’s incident mechanism? How to organize bubbling?
1. An operation in a webpage, such as clicking a button, will generate an event that can be detected by JS.
2. Event handling mechanism: IE is an event bubbling model and Firefox supports two event models at the same time, namely, capture event and bubbling event.
3、ev.stopPropation();
(The old IE methodev.cancelBubble=true;
)
- what isClosure, why do you want to use it?
Closure refers to a function that has access to variables in the scope of another function. The most common way to create closure is to create another function within one function and access local variables of this function through another function.
Closures can be used to break through scope chain and transfer variables and methods inside functions to the outside.Properties of Closures:
1. Nesting functions within functions;
2. Internal functions can refer to outer parameters and variables;
3. Parameters and variables will not be collected by the garbage collection mechanism
li
Node’sonclick
Events can correctly pop up the currently clickedli
Index
var nodes = document.getElementsByTagName('li');
for (var i = 0, len = nodes.length; i < len; i++) {
nodes[i].onclick = (function (i) {
return function () {
console.log(i);
}
})(i)
}
carry out
sayNum()
After that,sayNum()
The variables inside the closure still exist, while the variables of the functions inside the closure will not exist.
So that JS’s garbage collection mechanism GC will not collect itsayNum()
Resources taken up becausesayNum()
The execution of internal functions of depends onsayNum()
The variable in. This is a very straightforward description of the effect of closures.
function sayNum() {
var num = 666;
var sayLog = function () {
console.log(num);
};
num++;
return sayLog;
}
var sayLog = sayNum();
sayLog();//667
- In JS code
use strict;
What is the effect? What is the difference between using it?
use strict
It is a (strict) operation mode added by ES6, which enables JS to operate under stricter conditions.The mode of making JS coding more standardized eliminates some unreasonable and imprecise aspects of JS syntax and reduces some weird behaviors.
The default support of the trough cake features will be disabled, such as cannot be usedwith
, and cannot assign values to global variables under unexpected circumstances;
For the display declaration of global variables, functions must be declared at the top level, and functions cannot be declared in non-function code blocks.arguments.callee
Also not allowed to use;
Eliminate some unsafe aspects of code operation, ensure the safety of code operation, and limit the number ofarguments
Under strict modeeval
Functions behave differently from non-strict patterns.Improve compiler efficiency and speed;
- How to judge whether an object belongs to a class?
Use
instanceof
if (a instanceof Person) {
console.log("yes");
}
- Explain
new
Operator?
1. Create an empty object, and
this
Variable refers to the object and inherits the prototype of the function.
2. Attributes and methods are added tothis
In the referenced object;
3, the newly created object bythis
Referenced and finally implicitly returnedthis
.
var obj = {};
obj.__proto__ = Base.prototype;
Base.call(obj);
- JS
hasOwnProperty
Function, the prototype will not be found when searching for objects, explain in detail?
JS
hasOwnProperty
The function method returns a Boolean value indicating whether an object has a property with the specified name.
This method cannot check whether the attribute exists in the prototype chain of the object;
This attribute must be a member of the object itself.Usage:
Object.hasOwnProperty(proName)
Where parametersobject
Is a required option. An instance of an object.proName
Is a required option. The string value of an attribute name.If
object
The attribute with the specified name, JShasOwnproperty
Function method returnstrue
And vice versafalse
.
- What do you know about JSON?
JSON
Is a lightweight data exchange format.
It is a subset based on JS. The data format is simple, easy to read and write, and occupies less bandwidth.
JSON
String conversion toJSON
Object:
var obj = eval('(' + str + ')');
var obj = str.parseJSON();
var obj = JSON.parse(str);
JSON
Object toJSON
String:
var last = obj.toJSONString();
var last = JSON.stringify(obj);
- What are the delayed loading methods of JS?
defer
Andasync
, dynamic DOM creation (most used), asynchronous JS loading on demand
-
Ajax
What is it? How to create aAjax
?
Asynchronous transmission +JS+XML
Asynchronous: when sending a request to the server, you don’t have to wait for the result, but you can do other things at the same time, and when the result is available, you will follow up according to the settings.
At the same time, the page will not be refreshed as a whole, providing a user experience.1. Create
XMLHTTPRequest
Object, that is, to create an asynchronous call object;
2. Create a new HTTP request and specify the method, URL and authentication information of the HTTP request;
3. Set up a function to respond to HTTP request status changes;
4. Send HTTP Request
5. Obtain the data returned by asynchronous call
6. Use JS and DOM to realize local refresh
-
Ajax
Solve the browser cache problem?
1. In
ajax
Add before sending request
AjaxObj.setRequestHeader("IF-Modified-Since","0");
2. In
ajax
Add before sending request
AjaxObj.setRequestHeader("Cache-Control", "no-cache");
3. Add a random number after the URL:
"fresh=" + Math.random();
4. Add a timestamp after the URL:
"nowtime=" + new Date().getTime();
5. If jQuery is used, then
$.ajaxSetup({cache: false});
. All such pagesajax
This statement is executed without saving cache records.
- What is the difference between synchronous and asynchronous?
Synchronization: different processes are adjusted in order to accomplish a certain task cooperatively (throughBlocking,awakenSuch as way).
Synchronization: browser access server request, page refresh, resend request, wait for request to complete, page refresh displays new content, and so on and so forth.
Asynchronous: the browser accesses the server request, operates the page, and the browser backend makes the request. Wait for the request to complete and the page will not refresh to display the new content.
- How to solve the cross-domain problem?
jsonp
、iframe
、window.name
、window.postMessage
, set up the proxy page on the server
-
AMD
、CMD
The standard but don’t?
AMD
Asynchronous module definition, all modules will be loaded asynchronously, module loading will not affect the following statements.
All statements that depend on certain modules are placed in callback functions.Difference:
1. AMD is executing ahead of schedule and CMD is delaying execution for the dependent modules.
2. CMD advocates reliance on proximity while AMD advocates reliance on proximity.
//AMD
define(['./a', './b'], function (a, b) {//依赖必须一开始就写好
a.doSomething();
b.doSomething();
});
//CMD
define(function (require, exports, module) {
var a = require('./a');
a.doSomething();
var b = require('./b');//依赖可以就近写
b.doSomething();
});
-
document.write
AndinnerHTML
The difference?
document.write
You can only return to the entire page.innerHTML
Part of the page can be redrawn
-
DOM
Actions-Add, Remove, Move, Assign, Create and Find Nodes?
1. Create a new node
createDocumentFragment();//创建一个DOM片段
createElement();//创建一个具体的元素
createTextNode();//创建一个文本节点
2. Add, Remove, Replace, Insert
appendChild();//添加
removeChild();//移除
replaceChild();//替换
insertBefore();//在已有的子节点前插入一个新的子节点
3. Search
getElementsByTagName();//通过标签名
getElementsByName();//通过元素的Name属性的值(IE容错能力较强,会得到一个数组,其中包括id等于name值)
getElementById();//通过元素id,唯一性
-
jquery.extend
Andjquery.fn.extend
The difference?
jquery.extend
Forjquery
Class to add class methods, can be understood as adding static methodsjquery.fn.extend
:
Source codejquery.fn=jquery.prototype
Yesjquery.fn
The expansion of, is forjquery
Class to add member functions
Use:jquery.extend
Expansion, Need to Passjquery
Class, andjquery.fn.extend
Extension, alljquery
Instances can be called directly.
- How to Optimize jQuery?
Based on
class
The performance of the selector for is relative toid
Selectors are expensive because they need to traverse all DOM elements.DOM, which is frequently operated, is cached before operation. Use
jQuery
The chain call is better. such asvar str=$("a").attr("href");
for (var i = size, len = arr.length; i < len; i++) {}
- How do you determine whether the current script is running in a browser or a Node environment? (Ali)
this === window ? 'browser' : 'node';
Through judgmentglobal
Is the objectwindow
If it is notwindow
, the current script is not running in the browser.
- Which operations cause memory leaks?
The garbage collector defines scan objects and calculates the number of other objects that refer to each object. If the number of references to an object is
0
(No other object has referenced the object) or the only reference to the object is circular, then the memory of the object can be reclaimed.
setTimeout
The first parameter of the uses a string instead of a function, causing a memory leak.
Closure, console log, loop (a loop occurs when two objects reference each other and remain with each other)
- Using JS to Realize Thousands Separator?
function commafy(num) {
return num && num
.toString()
.replace(/(\d)(?=(\d{3})+\.)/g, function ($0, $1) {
return $1 + ',';
})
}
- Using JS to Get File Extension?
function getFileExtension(filename) {
return filename.splice((filename.ladtIndexOf(".") - 1 >>> 0) + 2);
}
String.lastIndexOf()
The method returns the specified value, the last occurrence in the string calling the method, or if it is not found-1
.
Forfilename
And.hiddenfile
,lastIndexOf
The return values of are0
And-1
.String.prototype.splice()
Extracts the file extension from the computed index. If the index is larger than the length of the file name, the result is""
.
- What is the implementation principle of webpack hot update?
1、
webpack
Compile time, for those requiring hot updatesentry
Inject a hot update code (EventSource
Communications)
2. After the page is opened for the first time, the server and the client pass throughEventSource
Establish communication channels and transfer the nexthash
Back to front
3. The client obtainshash
Thishash
It will be used as the next request serverhot-update.js
Andhot-update.json
Thehash
4, modify the page code,webpack
After listening to the file modification, start compiling and send it after compilingbuild
Message to client
5. The client obtainshash
After success, the client constructshot-update.js
Thescript
Link, then bash into the main document
6、hot-update.js
After successful insertion, executehotAPI
ThecreateRecord
Andreload
Method to get the of the componentrender
Methods, torender
Component, thus realizing UI no refresh update.
ES6
-
Object.is()
Compared with the original comparison operator===
、==
The difference?
==
Judging, type conversion will be carried out during comparison===
Judgments (strict judgment). No implicit type conversion is performed during comparison, and different types will be returned.false
Object.is()
In===
On the basis of judgment, special treatment has been carried out.NaN
、-0
And+0
, guarantee-0
And+0
No longer the same, butObject.is(NaN,NaN)
Will returntrue
- How to reconstruct the page?
Website reconstruction: optimize the website without changing the UI, and maintain a consistent UI while expanding.
For traditional websites, refactoring is usually:
1. Formtable
Change the layout todiv+css
2. Make the front end of the website compatible with modern browsers
3. Optimization of Mobile Platform
4. Optimize SEOIn-depth website reconstruction should consider:
1. Reduce the coupling between codes
2. Keep the code flexible
3, in strict accordance with the specification to write code
4. Design Extensible API
5, replace the old framework, language
6. Enhance user experience
7. Optimization of Speed1. compress JS, CSS,
image
Such as front-end resources (usually solved by the server)
2. Program Performance Optimization (Data Reading and Writing)
3. Use CDN to speed up resource loading
4. optimization of JS DOM
5. File Cache of HTTP Server
- List IE’s different features from other browsers?
Event: The element that triggered the event is considered the target (
target
)。 In IE, targets are contained inevent
Object’sSRCElement
Attributes;Get character code: if the key represents a character (
shift
、Ctrl
、Alt
Except) IE’skeyCode
Returns the character codeunicode
, the code of keys in DOM is separated from the characters. To obtain the character code, you need to usecharCode
Attributes;Default behavior for blocking an event: the default behavior for blocking an event in IE must be
returnValue
The property is set tofalse
, Firefox browser need to callpreventDefault()
Methods.Stop event bubbling, prevent further bubbling in IE, need to set
cancelBubble
Fortrue
, Firefox need to callstopPropagation()
.
- Explain graceful degradation and gradual enhancement?
Elegant downgrade: Web sites can work normally in all new browsers. If users are using old browsers, the code will downgrade the old version of IE to make it experience some form of downgrade on old browsers without being completely unusable.
For example:border-shadow
Progressive enhancement: Starting from the basic functions supported by all browsers, gradually add those functions only supported by new versions of browsers, and add additional styles and functions to the page that will not affect the basic browsers. When supported by browsers, they will be presented and play a role by themselves.
For example: default useflash
Upload, but if the browser supports the file upload function of HTML5, then use HTML5 to achieve a better experience.
- How do Web applications actively push Data from the server to the client?
HTML5
WebSocket
Invisibleiframe
WebSocket
viaflash
XHR
Long time connectionXHR Multipart Streaming
<script>
Long-term connection of tags (cross-domain)
- What are the advantages and disadvantages of Node?
Advantages:
Because Node is event-driven and non-blocking, it is very suitable for handling concurrent requests.
Therefore, proxy servers built on Node perform much better than servers implemented by other technologies, such as Ruby.
In addition, the client code interacting with Node proxy server is written in JS language, so both the client and server are written in the same language.Disadvantages:
Node is a relatively new open source project, so it is not very stable, always changing, and lacks enough third-party library support.
- Which front-end performance optimization methods have you used?
1. Reduce the number of HTTP requests:
CSS Sprites
、JS
、CSS
Source code compression, control picture size; Web pageGzip
, CDN hosting,data
Cache, picture server
2. Front-end template: JS+ data to reduce bandwidth waste caused by HTML tags. Front-end uses variables to save AJAX request results. Each time local variables are operated, there is no need to request and the number of requests is reduced.
3. UseinnerHTML
Replace DOM operations, reduce DOM operations and optimize JS performance
4. When there are many styles to be set, setclassName
Instead of direct operationstyle
5. Use less global variables and cache DOM node search results. Reduce IO read operations.
6. Avoid usingCSS
Expression, also known as dynamic attribute
7. Preload the picture, put the stylesheet at the top, put the script at the bottom, and add a timestamp.
8. Avoid using it in the theme layout of the pagetable
,table
The content will not be displayed until it has been completely downloadeddiv+css
The layout is slow.There is a unified idea for common websites, which is to optimize to the front end as much as possible, reduce database operations and reduce disk IO read and write.
Optimizing to the front end means that without affecting the function and experience,
What can be executed on the browser is not executed on the server side.
Those that can be returned directly on the cache server should not be executed on the application server.
The results that can be directly obtained by the program should not be obtained externally.
Data that can be obtained locally should not be obtained remotely.
Do not fetch the memory that can be fetched from the disk.
Don’t go to the database to query those in the cache.Reducing database operations refers to reducing the number of updates, caching results, reducing the number of queries, and allowing programs to complete the operations performed by the database as much as possible (e.g.
join
Query),
Reducing disk IO means not using file system as cache as much as possible, reducing the number of times of reading and writing files, etc.
- What are the HTTP status codes? What do they stand for?
Simple version:
100
–continue
: Continue, generally sendpost
When requested, senthttp header
After that, the server side will return this information to indicate confirmation, and then send specific parameter information.200
–OK
: return information normally201
–created
: The request succeeded and the server created a new resource202
–Accepted
: The server has accepted the request but has not yet processed it
301
–Moved Permanently
: the requested web page has been permanently moved to the new location302
–Found
: temporary redirection303
–See Other
: temporary redirection and always useGET
Request newURI
304
–Not Modified
: the requested web page has not been modified since the last request400
–Bad Request
: The server cannot understand the format of the request and the client should not attempt to initiate the request again with the same content
401
–Unauthorized
: request is not authorized403
–Forbidden
: no access404
–Not Found
: Unable to find how to connect withURI
Matching resources
500
–Internal Server Error
: the most common server-side errors503
–Server Unavailable
: The server side is temporarily unable to process the request (possibly overload or maintenance)Full version:
1**
(Information Class): Indicates that the request is received and processing continues100
-Customers must continue to make requests101
-The client requires the server to convert the HTML protocol version according to the request.
2**
(Response Successful): Indicates that the action was successfully received, understood and accepted200
-Indicates that the request was successfully completed and the requested resource is sent back to the client201
-prompt to know the new fileURL
202
-Accepted and processed, but the processing was not completed.203
-The returned information is uncertain or incomplete204
-request received but return message empty205
-The server has completed the request, and the user agent must reset the files that have been browsed currently.206
-the server has already completed some of the user’sGET
Request
3**
(Redirect Class): Further processing must be accepted in order to complete the specified action300
-The requested resources can be obtained from several sources.301
-this web page has been permanently transferred to another oneURL
302
-the requested web page is transferred to a new address, but customer access continues through the originalURL
Address, Redirection, NewURL
Will be inresponse
hit the targetLocation
, the browser will use the newURL
Send out new onesrequest
.303
-Advise customers to visit other placesURL
Or access method304
-The requested webpage has not been modified since the last request. When the server returns this response, it will not return the webpage content, which means the last document has been cached and can be used continuously.305
-The requested resource must be obtained from the address specified by the server306
-Codes used in the previous version of HTTP are no longer used in the current version.307
-Affirming the temporary deletion of the requested resources
4**
(Client Error Class): The request contains incorrect syntax or cannot be executed correctly400
-The client request has syntax errors and cannot be understood by the server.
401
-The request is not authorized. This status code must matchWWW-Authenticate
The header fields are used together
HTTP401.1
-Unauthorized: Login Failed
HTTP401.2
-Unauthorized: Login failed due to server configuration problem
HTTP401.3
-ACL prohibits access to resources
HTTP401.4
-Unauthorized: Authorization Denied by Filter
HTTP401.5
-Unauthorized: ISAPI or CGI authorization failed
402
-The reservation is validChargeTo
Head response
403
-No access, server receives request but refuses to provide service
HTTP403.1
-Prohibit Access: Prohibit Executable Access
HTTP403.2
-No Access: No Read Access
HTTP403.3
-No Access: No Write Access
HTTP403.4
-No Access: SSL Required
HTTP403.5
-No Access: SSL Required128
HTTP403.6
-Access Denied: IP Address Denied
HTTP403.7
-No Access: Require Customer Certificate
HTTP403.8
-No Access: No Site Access
HTTP403.9
-No Access: Too Many Users Connected
HTTP403.10
-No Access: Invalid Configuration
HTTP403.11
-No Access: Password Change
HTTP403.12
-Access Denied: Mapper Denies Access
HTTP403.13
-No Access: Customer Certificate Revoked
HTTP403.15
-No access: too many customer access permits
HTTP403.16
-No Access: The customer certificate is not trusted or invalid
HTTP403.17
-Access Forbidden: The customer certificate has expired or is not yet valid
404
-One404
An error indicates that the server can be connected, but the server cannot obtain the requested web page and the requested resource does not exist.405
-Users inRequest-Line
The method of field definition is not allowed.406
-according to the user sentAccept
Head, requested resource is inaccessible407
-similar401
, the user must first be authorized on the proxy server408
-The client did not complete the request within the time specified by the user.409
-request cannot be completed for current resource status410
-This resource no longer exists on the server and there is no further reference address411
-Server Rejects User DefinedContent-Length
Attribute request412
-One or more request header fields are incorrect in the current request413
-The requested resource is larger than the size allowed by the server414
-The requested resource URL is longer than the length allowed by the server415
-The requested resource does not support the requested project format416
-The request includesRange
The request header field does not exist within the current request resource range.Range
Indicates a value that the request does not containIf-Rane
Request header field417
-The server did not meet the requestExpect
If the expected value specified in the header field is a proxy server, the next level server may not be able to meet the request.
5**
(Server Error Class): The server cannot execute a correct request correctly
HTTP500
-The server encountered an error and could not complete the request.
HTTP500.100
-Internal Server Error-ASP Error
HTTP500.11
-server shutdown
HTTP500.12
-application restart
HTTP500.13
-Server Too Busy
HTTP500.14
-Invalid application
HTTP500.15
-Request not allowedglobal.asa
Error
501
-Not achievedHTTP
502
-gateway error
HTTP503
-The server is currently unavailable due to overload or shutdown maintenance, and may return to normal after a period of time.
- What happens when a page is displayed from URL input to page loading? (The more detailed the process, the better)
From URL specification, HTTP protocol, DNS, CDN, database query to browser parsing, CSS rule construction,
layout
、paint
、onload/domready
JS execution, JS API binding, etc.1. The browser will open a thread to process the request, and if it is HTTP protocol, the URL will be analyzed and judged according to the Web method.
2. Call the corresponding method in the browser kernel, such aswebview
hit the targetloadUrl
Methods;
3, acquiring the IP address of the website through DNS analysis, setting UA and other information to send out a second GET request;
4. Memorize HTTP protocol sessions, and the client sends a header (request header);
5. Enter the web server on the Web Server, such as Accept, Tomcat, Node.js and other servers;
6. Enter deployed back-end applications, such as PHP, Java, JavaScript, python, etc., and find the corresponding request processing;
7. End-of-process feedback header. If the browser has accessed it and there are corresponding resources in the cache, it will be compared with the last modification time of the server, and if it is consistent, it will be returned304
;
8. The browser starts downloading HTML documents (response header, status code200
), while using cache;
9. document tree establishment: specify MIME type files (e.g. css, js) according to mark request, and setcookie
;
10. The page starts rendering DOM, JS operates DOM according to DOM API, executes event binding, etc., and the page display is completed.The browser gives the requested URL to DNS domain name analysis, finds the real IP, and initiates a request to the server;
The server returns the data after the background processing is completed, and the browser receives the file;
The browser parses the loaded resource syntax and establishes the corresponding internal data structure;
Load the parsed resource file and render the page display content.