[interview] 764 high frequency front-end development interview questions and answers sorting

Tell me about your understanding of closures

Closures are mainly used to design private methods and variables. The advantage of closures is that they can avoid the pollution of global variables. The disadvantage is that closures will reside in memory and increase memory usage. Improper use can easily lead to memory leakage.

Closures have three characteristics:
 1. Function nested function
 2. Internal functions can reference external parameters and variables
 3. Parameters and variables are not recycled by the garbage collection mechanism

Please talk about the disadvantages of cookies

cookie Although it provides convenience in persisting client data and shares the burden of server storage, it still has many limitations.

A maximum of 20 are generated under each specific domain name cookie
	1. IE6 Or lower version up to 20 cookie
	2. IE7 And later versions can end up with 50 cookie. 
	3. Firefox Up to 50 cookie
	4. chrome and Safari There are no hard restrictions
IE and Opera Will clean up the least recently used cookie,Firefox Random cleaning cookie. 
cookie The maximum is about 4096 bytes. For compatibility, it can not exceed 4095 bytes.

IE It provides a storage method that can persist user data, called userdata,from IE5.0 Start supporting. Up to 128 per data K,Up to 1 per domain name M. This persistent data is placed in the cache. If the cache is not cleaned up, it will always exist.

Advantages: high scalability and availability
	1. Through good programming, the control is saved in cookie Medium session The size of the object.
	2. Through encryption and secure transmission technology( SSL),reduce cookie The possibility of being cracked.
	3. Only in cookie Store insensitive data in the, even if it is stolen, there will be no significant loss.
	4. control cookie So that it won't last forever. The thief is likely to get an expired one cookie. 
	5. 
Disadvantages:
	1.`Cookie`Restrictions on quantity and length. each domain There can only be 20 at most cookie,each cookie Length cannot exceed 4 KB,Otherwise it will be cut off.
	2.Security issues. If cookie If someone intercepts it, that person can get all the information session Information. Even encryption doesn't help, because the interceptor doesn't need to know cookie He just forwards it as it is cookie You can achieve your goal.
	3.Some states cannot be saved on the client. For example, to prevent duplicate submission of forms, we need to save a counter on the server side. If we save this counter on the client, it won't work.

Browser local storage

In later browsers, js Provided sessionStorage and globalStorage. stay HTML5 Provided in localStorage To replace globalStorage. 

html5 Medium Web Storage It includes two storage methods: sessionStorage and localStorage. 

sessionStorage Used to store a session locally( session)Data that can only be accessed by pages in the same session, and the data will be destroyed when the session ends. therefore sessionStorage It is not a persistent local storage, but only session level storage.

and localStorage For persistent local storage, data will never expire unless it is actively deleted.

Differences between web storage and cookie s:

Web Storage Concept and cookie Similar, the difference is that it is designed for larger capacity storage. Cookie The size of is limited, and every time you request a new page Cookie In addition, the bandwidth will be wasted in the past cookie You also need to specify the scope, which cannot be called across domains.

besides, Web Storage have setItem,getItem,removeItem,clear And other methods, unlike cookie The front-end developer needs to encapsulate it himself setCookie,getCookie. 

however cookie It is also indispensable: cookie The role of is to interact with the server as HTTP Part of the norm, and Web Storage Just to "store" data locally

Browser support in addition to IE7And below are not supported, other standard browsers are fully supported(ie and FF Need in web Running in the server),It is worth mentioning that IE Always do good things, for example IE7,IE6 Medium userData Actually javascript Local storage solutions. Through simple code encapsulation, it can be unified to all browsers web storage. 

localStorage and sessionStorage All have the same operation method, such as setItem,getItem and removeItem etc.

The difference between cookie and session:

 1. cookie The data is stored on the customer's browser, session The data is placed on the server.
 2. cookie It's not very safe. Others can analyze the data stored locally COOKIE And carry out COOKIE deception
    For safety reasons, it should be used session. 
 3. session It will be saved on the server for a certain period of time. When access increases, it will occupy the performance of your server
     To mitigate server performance, you should use COOKIE. 
 4. single cookie The saved data cannot exceed 4 K,Many browsers limit a site to a maximum of 20 cookie. 
 5. So I suggest:
    Store important information such as login information as SESSION
    If other information needs to be retained, it can be placed in COOKIE in

CSS related issues

What is the difference between display:none and visibility:hidden?

display:none  Hide the corresponding element, no longer allocate space to it in the document layout, and the elements on all sides will close, just as it never exists.
visibility:hidden  Hide the corresponding elements, but keep the original space in the document layout.

What is the difference between link and @ import in CSS?

 1. link belong to HTML Label, and@import yes CSS Provided;
 2. When the page is loaded, link Will be loaded at the same time, and@import Quoted CSS It will wait until the page is loaded;
 3. import Only in IE5 The above can be identified, and link yes HTML Label, no compatibility issues; 
 4. link The weight of the style of the mode is higher than@import Weight of.

Position: similarities and differences between absolute and float attributes

A: common ground:
Setting for inline elements`float`and`absolute`Property, you can separate the element from the document flow, and you can set its width and height.

B: difference:
float Will still occupy a position, position Overwrites other elements in the document stream.

Introduce the box sizing attribute?

box-sizing Attribute is mainly used to control the parsing mode of the box model of the element. The default value is content-box. 
content-box: Keep elements W3C Standard box model. Width of element/Height by border + padding + content Width of/Height determination, setting width/height Attributes refer to content Partial width/high
border-box: Keep elements IE Traditional box model( IE6 The following versions and IE6~7 Weird pattern). set up width/height Attributes refer to border + padding + content

Under the standard browser, press W3C The specification analyzes the box model. Once the border or inner distance of the element is modified, the box size of the element will be affected, and the box size of the element will have to be recalculated, thus affecting the layout of the whole page.

What are CSS selectors? Which attributes can be inherited? How is the priority algorithm calculated? What are the new pseudo classes in CSS3?

 - id Selector( # myid)
 - Class selector(.myclassname)
 - Label selector( div, h1, p)
 - Adjacent selector( h1 + p)
 - Sub selector( ul > li)
 - Descendant selector( li a)
 - Wildcard selector( * )
 - Attribute selector( a[rel = "external"])
 - Pseudo class selector( a: hover, li:nth-child)
  • Inheritable styles: font size, font family color, text indent;
  • Non inheritable styles: border padding margin width height;
  • The principle of priority proximity, and in the case of the same weight, the closest style definition shall prevail;
  • The loading style shall be subject to the positioning of the last loading;

Priority is:

!important >  id > class > tag  
important Higher priority than inline,But inline ratio id Higher

Examples of new pseudo classes in CSS3:

p:first-of-type Select the first element that belongs to its parent element <p> Each of the elements <p> Element.
p:last-of-type  Select the last element that belongs to its parent element <p> Each of the elements <p> Element.
p:only-of-type  Select a unique element that belongs to its parent element <p> Each of the elements <p> Element.
p:only-child    Select each of the unique child elements that belong to its parent element <p> Element.
p:nth-child(2)  Select each element that belongs to the second child element of its parent element <p> Element.
:enabled  :disabled Controls the disabled state of the form control.
:checked        The radio box or check box is selected.

The value of position, relative and absolute are positioned relative to who?

absolute 
        The element that generates absolute positioning is not relative to the positioning of the nearest level static The parent element of the.

fixed (old IE (not supported)
    Generates an absolutely positioned element that is positioned relative to the browser window. 

relative 
    Generate a relatively positioned element and locate it relative to its position in the ordinary flow. 

static  Default value. Without positioning, the element appears in the normal flow

What are the new features of CSS3?

CSS3 Realize fillet( border-radius),Shadow( box-shadow),
Add special effects to text( text-shadow,),Linear gradient( gradient),Spin( transform)
transform:rotate(9deg) scale(0.85,0.90) translate(0px,-30px) skew(-9deg,0deg);//Rotate, zoom, position, tilt
 Added more CSS Selector multi background rgba 
stay CSS3 The only pseudo element introduced in is::selection.
Media query, multi column layout
border-image

What is the difference between XML and JSON?

 1. Data volume.
	JSON be relative to XML Generally speaking, the volume of data is small and the transmission speed is faster.
 2. Data interaction.
	JSON And JavaScript The interaction of is more convenient, easier to analyze and process, and better data interaction.
 3. Data description.
	JSON Descriptive ratio of data XML Poor.
 4. Transmission speed.
	JSON Is much faster than XML. 

Understanding of BFC specification?

 BFC,Block level formatting context, a new one is created BFC The box is arranged independently. The style of the child elements in the box will not affect the external elements. In the same BFC Two adjacent block level boxes in the vertical direction (related to the layout direction) margin Folding occurs.
(W3C CSS 2.1 A concept in a specification that determines how an element lays out its content and how it relates and interacts with other elements.)

Explain CSS sprites and how you want to use them on your page or website.

CSS Sprites In fact, it is to integrate some background pictures in the web page into a picture file for reuse CSS Yes“ background-image","background- repeat","backgroun

html part

What's your understanding of semantics?

 1. Removing or losing styles can make the page present a clear structure
 2. advantageous to SEO: Establishing good communication with search engines helps crawlers capture more effective information: crawlers rely on tags to determine the context and the weight of each keyword;
 3. Facilitate other devices (such as screen readers, blind readers, mobile devices) to render web pages in a meaningful way;
 4. It is easy for the team to develop and maintain, semantic and more readable. It is an important trend of the web page in the next step. Follow W3C Standard teams follow this standard, which can reduce differentiation.

What is the role of Doctype? How to distinguish between strict mode and hybrid mode? What do they mean?

 1. <!DOCTYPE> The declaration is at the top of the document and at the top <html> Before label. Tells the browser which mode to render the document. 
 2. Strict pattern layout and JS The operating mode is the highest standard supported by the browser.
 3. In hybrid mode, the page is displayed in a relaxed backward compatible manner. Simulate the behavior of older browsers to prevent the site from not working.
 4. DOCTYPE Non existence or incorrect format can cause the document to be rendered in mixed mode.   

How many Doctype document types do you know?

The label can declare three DTD Type, representing strict version, transitional version and framework based version respectively HTML file.
	HTML 4.01 Three document types are specified: Strict,Transitional as well as Frameset. 
	XHTML 1.0 Three types are specified XML Document type: Strict,Transitional as well as Frameset. 
	Standards (Standard mode (i.e. strict rendering mode) is used to render web pages that follow the latest standards, and Quirks(Inclusive mode (i.e. loose rendering mode or compatible mode) is used to render web pages designed for traditional browsers.

HTML and XHTML -- what's the difference between them

difference:
 1. All tags must have a corresponding end tag
 2. All tag element and attribute names must be lowercase
 3. be-all XML Tags must be nested properly
 4. All attributes must be in quotation marks""Enclose
 5. Put all<and&Special symbols are represented by codes
 6. Assign a value to all attributes
 7. Don't make in comments“--"
 8. Pictures must have explanatory text

Common compatibility issues?

 1. png24 Bit picture in iE6 The background appears on the browser, and the solution is to make it PNG8.You can also refer to a script for processing.

 2. Browser default margin and padding Different. The solution is to add a global*{margin:0;padding:0;}To unify.

 3. IE6 Double margin bug:Block attribute label float After that, there are rampant margin In case ie6 display margin Larger than set. 

 4. float ie Double distance generated( IE6 Bilateral distance problem: in IE6 Next, if floating is set for the element and margin-left or margin-right,margin The value is doubled.)
  #box{ float:left; width:10px; margin:0 0 0 100px;} 

 In this case IE Will produce 20 px Distance, the solution is in float Add to the label style control of——_display:inline;Convert it to an inline attribute.(_This symbol has only ie6 Can identify)

 5.  Gradually eliminate the part from the whole by means of gradual identification. 

  First, clever use“\9"This mark will IE The viewer separates from all situations. 
  Then, use it again“+"take IE8 and IE7,IE6 Separate, so IE8 Has been independently identified.

  css
      .bb{
       background-color:#f1ee18;/* All identification*/
      .background-color:#00deff; /*IE6, 7 and 8 identification*/
      +background-color:#a200ff;/*IE6 and 7 identification*/
      _background-color:#1e0bd1;/*IE6 identification*/ 
      } 

 6.  IE lower,You can use the method of getting general properties to get custom properties,
   You can also use getAttribute()Get custom properties;
   Firefox lower,Only use getAttribute()Get custom properties. 
   resolvent:Unified adoption getAttribute()Get custom properties.

 7. IE lower,event Object has x,y attribute,But no pageX,pageY attribute; 
  Firefox lower,event Object has pageX,pageY attribute,But no x,y attribute.

 8. Solution: (conditional comment) the disadvantage is that IE Additional may be added under the browser HTTP Number of requests.

 9. Chrome In the Chinese interface, it will be less than 12 by default px The text of is mandatory according to 12 px display, 
  Can be added by CSS attribute -webkit-text-size-adjust: none; solve.

 10. After hyperlink access hover The style will not appear. The hyperlink style that has been clicked and accessed will no longer have hover and active The solution is to change CSS Order of attributes:
L-V-H-A :  a:link {} a:visited {} a:hover {} a:active {}

 11. Weird mode problem: missing write DTD Statement, Firefox The web page will still be parsed according to the standard mode, but in IE Weird mode will be triggered in. In order to avoid unnecessary trouble caused by strange patterns, it is best to develop writing DTD Good habit of declaration. Now you can use[html5](http://www.w3.org/TR/html5/single-page.html) recommended writing method: ` < DOCTYPE HTML >`

 12. Up and down margin Coincidence problem
ie and ff Both exist, two adjacent div of margin-left and margin-right It won't coincide, but margin-top and margin-bottom But it will coincide.
Solutions, develop good coding habits, and adopt margin-top Or both margin-bottom. 
 13. ie6 yes png Poor image format support(Reference a script for processing)

Explain floating and how it works? Techniques for clearing floats

Floating elements are separated from the document flow and do not occupy space. The floating element touches the border containing it or stays in the border of the floating element.
 1. Use an empty label to clear the float.
   This method is to add an empty label definition after all floating labels css clear:both. The disadvantage is the addition of meaningless labels.
 2.use overflow. 
   Add to the parent tag that contains the floating element css attribute overflow:auto; zoom:1; zoom:1 For compatibility IE6. 
 3. use after Dummy object clear float.
  	This method is only applicable to non IE browser. The specific writing method can refer to the following examples. Pay attention to the following points in use. 1, This method must be set in the pseudo object that needs to clear the floating element height:0,Otherwise, the element will be several pixels higher than the actual;

Problems caused by floating elements and solutions?

Problems caused by floating elements:
 1. The height of the parent element cannot be extended, affecting the elements at the same level as the parent element
 2. Non floating elements (inline elements) of the same level as floating elements follow
 3. If not the first element floats, the elements before the element also need to float, otherwise it will affect the structure of the page display

resolvent:
Use clear:both in CSS; Property to clear the floating of elements can solve problems 2 and 3. For problem 1, add the following style and add clearfix style to the parent element:

.clearfix:after{content: ".";display: block;height: 0;clear: both;visibility: hidden;}
.clearfix{display: inline-block;} /* for IE/Mac */

Several methods to clear floating:

 1. Additional labeling method,<div style="clear:both;"></div>(Disadvantages: however, this method will add additional labels to make HTML The structure doesn't look concise enough.)
 2. use after Pseudo class
	#parent:after{
	    content:".";
	    height:0;
	    visibility:hidden;
	    display:block;
	    clear:both;
	    }
 3. Floating external element
 4. set up`overflow`by`hidden`perhaps auto

What is the difference between box models in browsers under IE 8

IE8 The width and height of elements defined in the box model of the following browsers do not include inner margins and borders

DOM operations -- how to add, remove, move, copy, create, and find nodes.

 1. Create a new node
	createDocumentFragment()    //Create a DOM fragment
	createElement()   //Create a concrete element
	createTextNode()   //Create a text node
 2. Add, remove, replace, insert
	appendChild()
	removeChild()
	replaceChild()
	insertBefore() //Insert a new child node before the existing child node
 3. lookup
	getElementsByTagName() //By label name
	getElementsByName()    //Through the value of the name attribute of the element (IE has strong fault tolerance and will get an array, including the one whose id is equal to the name value)
	getElementById()    //Uniqueness through element Id

What are the new features and elements of HTML5? How to deal with the browser compatibility of HTML5 new tags? How to distinguish between HTML and HTML5?

 1. HTML5 Not now SGML The subset is mainly about the increase of image, location, storage, multitasking and other functions.
 2. Drag release(Drag and drop) API 
	Better semantic content Tags( header,nav,footer,aside,article,section)
	Audio and video API(audio,video)
	canvas(Canvas) API
	Geography(Geolocation) API
	Local offline storage localStorage Store data for a long time, and the data will not be lost after the browser is closed;
	sessionStorage The data is automatically deleted after the browser is closed

	Form controls, calendar,date,time,email,url,search  
	New technology webworker, websocket, Geolocation

 3. Removed element
	Purely expressive elements: basefont,big,center,font, s,strike,tt,u;
	Elements that have a negative impact on availability: frame,frameset,noframes;
	support HTML5 New label:

 4. IE8/IE7/IE6 Support through document.createElement Method can be used to support these browsers HTML5 For new labels, after the browser supports new labels, you also need to add the default style of labels

 5. Of course, the best way is to directly use the mature framework, which is the most used html5shim frame
	<!--[if lt IE 9]> 
	<script> src="http://html5shim.googlecode.com/svn/trunk/html5.js"</script> 
	<![endif]--> 
	How to distinguish: DOCTYPE statement\New structural elements\Functional elements

Advantages and disadvantages of iframe?

 1. `<iframe>`advantage:
    Solve the loading problem of slow loading third-party content, such as icons and advertisements
    Security sandbox
    Parallel load script
2.`<iframe>`Disadvantages:
	iframe Will block the main page Onload event;
	Even if the content is empty, it takes time to load
	No meaning 

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

call localstorge,cookies And other local storage methods

The difference between thread and process

A program has at least one process,A process has at least one thread. 
The division scale of threads is smaller than that of processes, which makes the concurrency of multithreaded programs high. 
In addition, the process has an independent memory unit during execution, and multiple threads share memory, which greatly improves the running efficiency of the program. 
Threads are different from processes during execution. Each independent thread has an entry for program operation, sequential execution sequence and program exit. However, threads cannot be executed independently. They must be stored in the application program, and the application program provides multiple thread execution control. 
From a logical point of view, the significance of multithreading is that there are multiple execution parts in an application that can be executed at the same time. However, the operating system does not regard multiple threads as multiple independent applications

How do you optimize the files and resources of the website?

Expected solutions include:
	File merge
	File minimization/File compression
	use CDN trusteeship
	Use of cache (multiple domain names to provide cache)
	other

Please name three ways to reduce page load time.

 1. Optimize picture
 2.Selection of image format( GIF: There are few colors available, which can be used in some places with low color requirements) 
 3.optimization CSS(Compression merge css,as margin-top,margin-left...) 
 4.Web address followed by slash (e.g www.campr.com/Directory, which "file type or directory" this "directory is will be judged.) 
 5.Indicate the height and width (if the browser does not find these two parameters, it needs to calculate the size while downloading pictures. If there are many pictures, the browser needs to constantly adjust the page. This affects not only the speed, but also the browsing experience. 
   When the browser knows the height and width parameters, even if the picture cannot be displayed temporarily, the space of the picture will be vacated on the page, and then continue to load the following content. Thus, the loading time is faster and the browsing experience is better.) 
 6.reduce http Request (merge files, merge pictures).

What tools do you use to test the performance of your code?

Profiler, JSPerf(http://jsperf.com/nexttick-vs-setzerotimeout-vs-settimeout), Dromaeo

What is FOUC (no style content flashing)? How do you avoid FOUC?

FOUC - Flash Of Unstyled Content Document style flashing
<style type="text/css" media="all">@import "../fouc.css";</style> 
And quote CSS Document@import Is the culprit of this problem. IE The whole will be loaded first HTML Document DOM,Then import the external CSS File, therefore, on the page DOM Load complete to CSS There will be a period of time when the import is completed. The content on the page has no style. The length of this period is related to the network speed and computer speed.
The solution is surprisingly simple, as long as<head>Add one between<link>perhaps<script>Element is OK.

What is the difference between null and undefined?

  • null is an object representing "None", which is 0 when converted to a numerical value; undefined is an original value indicating "None", which is NaN when converted to a numerical value.
    When the declared variable has not been initialized, the default value of the variable is undefined.
  • null is used to indicate an object that does not exist. It is often used to indicate that a function attempts to return an object that does not exist.
  • undefined means "missing value", that is, there should be a value here, but it has not been defined. Typical usage is:
 - When a variable is declared but not assigned, it is equal to undefined. 
 - When calling a function, the parameter that should be provided is not provided, and the parameter is equal to undefined. 
 - Object has no assigned property, and the value of this property is undefined. 
 - When the function has no return value, it returns by default undefined. 
  • null means "no object", that is, there should be no value there. Typical usage is:
 1. As a parameter of a function, it means that the parameter of the function is not an object.
 2. As the end of the object prototype chain.

What exactly does the new operator do?

 1. Create an empty object, and this Variable references the object and inherits the prototype of the function.
 2. Properties and methods are added to this In the referenced object.
 3. The newly created object is created by this Referenced and finally implicitly returned this . 

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

What are the ways to delay the loading of js?

defer and async,Dynamic creation DOM Method (create) script,Insert into DOM After loading callBack),Asynchronous load on demand js

How to solve cross domain problems?

jsonp, document.domain+iframe,window.name,window.postMessage,Set up proxy page on server
jsonp The principle of is dynamic insertion script label
 See: detailed explanation for details js Cross domain problem

documen. The difference between write and innerHTML

document.write Only the entire page can be redrawn
innerHTML You can redraw part of the page

. call() and What are the differences and functions of apply()?

Function: dynamically change the running environment of a method of a class.
See: JavaScript *** function Function part

What actions can cause memory leaks?

A memory leak is any object that persists after you no longer own or need it.
The garbage collector periodically scans objects and counts the number of other objects that reference 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, the memory of the object can be reclaimed.

setTimeout Using a string instead of a function as the first argument to a will cause a memory leak.
Closure, console log, loop (a loop is generated when two objects refer to each other and retain each other)
See: detailed explanation js Variable, scope and memory

Scope and variable declaration promotion in JavaScript?

See: detailed explanation JavaScript Function mode

How to determine whether the current script is running in the browser or node environment?

Through judgment Global Whether the object is window,If not window,The current script is not running in the browser

Other questions?

What are the difficult technical problems you have encountered? How did you solve it?
List the features of IE that are different from other browsers?
What is graceful degradation and progressive enhancement?

Elegant downgrade: Web The site works well in all new browsers, and if users use older browsers, the code checks to see if they work properly. because IE Unique box model layout problem for different versions of IE of hack I've practiced it,Add candidates for browsers that can't support functions, so that they can degrade the experience in some form on old browsers without completely failing.
Progressive enhancement: start with the basic functions supported by all browsers and gradually add those functions only supported by new browsers,Add additional styles and features to the page that are harmless to the underlying browser. When the browser supports them, they will automatically appear and work.
See: css Learning summary (I)

What are the ways for WEB applications to actively push Data from the server to the client?

Javascript Data push
Commet: be based on HTTP Long server connection push technology
 be based on WebSocket Push scheme for
SSE(Server-Send Event): New method of server push data

How do you understand the position of front-end interface engineer? What are its prospects?

The front end is the programmer closest to the user, which is closer to the back end, database, product manager, operation and security.
 1. Realize interface interaction
 2. User experience improvement
 3. Yes Node.js,The front end can realize some things on the server side

The front end is the programmer closest to the user. The ability of the front end is to make the product evolve from 90 points to 100 points, or even better,
	Participate in the project and complete the effect drawing quickly and with high quality, accurate to 1 px;
	With team members, UI Communication with design and product manager;
	Good page structure, page reconstruction and user experience;
	handle hack,Compatible and write beautiful code format;
	Optimize the server and embrace the latest front-end technology.

What performance optimization methods do you have?

(For details, please see Yahoo's 14 performance optimization principles).
 1. reduce http Number of requests: CSS Sprites, JS,CSS Source code compression and image size control are appropriate; Webpage Gzip,CDN trusteeship, data Cache, image server.
 2. Front end template JS+Data, reduced due to HTML The bandwidth waste caused by tags is saved in variables at the front end AJAX Request result: local variables are operated each time, no request is needed, and the number of requests is reduced
 3. use innerHTML replace DOM Operation, reduce DOM Operation times, optimization javascript Performance.
 4. Set when there are many styles to set className Instead of direct operation style. 
 5. Use less global variables and cache DOM Results of node lookup. reduce IO Read operation.
 6. Avoid using CSS Expression(css expression)also called Dynamic properties(Dynamic properties). 
 7. Preload the picture, put the style sheet at the top, put the script at the bottom and time stamp it.
Details: http://segmentfault.com/blog/trigkit4/1190000000691919

What happens to a page from entering the URL to the completion of page loading and display?

There are four steps:
 1. When sending a URL When requested, ignore this URL yes Web Page URL still Web Of each resource on the page URL,The browser will open a thread to process the request, at the same time in the remote DNS Start a on the server DNS Query. This enables the browser to obtain the corresponding information of the request IP Address.
 2. Browser and remote Web Server pass TCP Three handshake negotiations to establish a TCP/IP connect. The handshake includes a synchronization message and a synchronization message-Reply message and a reply message, which are transmitted between the browser and the server. The handshake first attempts to establish communication by the client, then the server answers and accepts the request of the client, and finally the client sends the message that the request has been accepted.
 3. once TCP/IP When the connection is established, the browser will send a message to the remote server through the connection HTTP of GET Request. The remote server finds the resource and uses it HTTP The response returns the resource with a value of 200 HTTP The response status indicates a correct response.
 4. At this point, Web The server provides resource services, and the client starts downloading resources.

After the request is returned, it enters the front-end module we focus on
 In short, the browser will parse HTML generate DOM Tree,Secondly, according to CSS generate CSS Rule Tree,and javascript Can also be based on DOM API operation DOM
 Details: input from URL What happened in the process of receiving from the browser?

How do you manage your project?

The advance team must determine the global style( globe.css),Coding mode(utf-8) Etc;
 1. The writing habits must be consistent (for example, they are written in inheritance, and single styles are written in one line);
 2. The annotation style writer shall mark all modules in time (mark the place where the key style is called);
 3. Mark the page (such as the beginning and end of the page module);
 4. CSS Follow HTML It shall be stored in folders in parallel, and the names shall be unified (e.g style.css);
 5. JS It is stored and named in a folder JS Function based English translation.
 6. The pictures are integrated images.png png8 The use of format files shall be integrated as far as possible to facilitate future management 

Tell me about some of the most popular things recently? Which websites do you often visit?

Node.js,Mongodb,npm,MVVM,MEAN,three.js,React . 
Website: w3cfuns,sf,hacknews,CSDN,Muke, blog Park, InfoQ,w3cplus etc.

Several ways of creating javascript objects

 1. Factory mode
 2. Constructor Pattern 
 3. Prototype mode
 4. Mixed constructor and prototype pattern
 5. Dynamic prototype mode
 6. Parasitic constructor mode
 7. Safe constructor mode

Six methods of javascript inheritance

 1. Prototype chain inheritance
 2. Borrowing constructor inheritance
 3. Combinatorial inheritance(prototype+Borrowing construction)
 4. Prototype inheritance
 5. Parasitic inheritance
 6. Parasitic combinatorial inheritance
 Details: JavaScript Detailed explanation of inheritance method

ajax process

 1. establish XMLHttpRequest object,That is to create an asynchronous call object.
 2. Create a new HTTP request,And specify the HTTP Method of request URL And verification information.
 3. Set response HTTP Function requesting state change.
 4. send out HTTP request.
 5. Get the data returned by asynchronous call.
 6. use JavaScript and DOM Implement local refresh.
Details: JavaScript *** Ajax and Http Status word

Asynchronous loading and deferred loading

 1. Create a scheme for asynchronous loading: dynamic insertion script label
 2. adopt ajax To get js Code, and then through eval implement
 3. script Add on label defer perhaps async attribute
 4. Create and insert iframe,Let it execute asynchronously js
 5. Delayed loading: some js The code is not needed immediately when the page is initialized, but later in some cases.

Front end security issues?

sql injection principle

By putting SQL Insert command into Web The form submits or inputs the query string of the domain name or page request, and finally deceives the server to execute malicious SQL Command.

In general, there are the following points:
 1. Never trust the user's input. To verify the user's input, you can use regular expressions or limit the length of single quotation marks and double quotation marks"-"Carry out conversion, etc.
 2. Never use dynamic assembly SQL,You can use parameterized SQL Or directly use stored procedures for data query and access.
 3. Never use a database connection with administrator privileges. Use a separate database connection with limited privileges for each application.
 4. Do not store confidential information in clear text, please encrypt or hash Lose passwords and sensitive information.

XSS principle and Prevention

Xss(cross-site scripting)An attack is an attack by an attacker Web Insert malicious code into the page html Label or javascript code. For example: the attacker puts a in the forum
 The seemingly safe link swindles the user to click and steal cookie User private information in; Or the attacker adds a malicious form to the forum,
When the user submits the form, it transmits the information to the attacker's server instead of the trusted site that the user thought.

XSS prevention methods

 1. The code needs to carefully check the length and alignment of the places and variables entered by the user<",">",";","'"And other characters are filtered; Secondly, any content must be written before it is written to the page encode,Avoid accidentally html tag Get it out. If this aspect is done well, at least more than half of the traffic can be blocked XSS Attack.
 2. Avoid direct cookie Disclose user privacy in, for example email,Passwords, etc.
 3. By making cookie And system ip Bind to reduce cookie Danger after leakage. So the attacker gets cookie It has no practical value and cannot be replayed.
 4. Try to use POST Not GET Submit Form 

What is the difference between XSS and CSRF?

XSS It is to obtain information without knowing the code and data package of other user pages in advance. CSRF It is to complete the specified action instead of the user. You need to know the code and data package of other user pages.

To complete once CSRF To attack, the victim must complete two steps in turn:
 1. Log in to trusted sites A,And generate locally Cookie. 
 2. Don't log out A In case of, visit dangerous websites B. 

Defense of CSRF

 1. Server side CSRF There are many ways and methods, but the general idea is the same, that is, to increase the pseudo-random number on the client page.
 2. Use verification code

How many resources can ie and chrome download in parallel

IE6 Two concurrent, iE7 After the upgrade, there are 6 Concurrent Versions and 6 subsequent versions
Firefox,chrome Six, too

How to implement inheritance in javascript and how to avoid object sharing on the prototype chain

Use the mixed mode of constructor and prototype chain to realize inheritance and avoid object sharing. You can refer to the classic extend()Functions, which are encapsulated in many front-end frameworks, use an empty function as an intermediate variable

grunt, YUI compressor and google clojure are used for code compression.

YUI Compressor Is a compression JS and CSS Documentation, tools used Java development.

usage method:
	//Compress JS
	java -jar yuicompressor-2.4.2.jar --type js --charset utf-8 -v src.js > packed.js
	//Compress CSS
	java -jar yuicompressor-2.4.2.jar --type css --charset utf-8 -v src.css > packed.css
 For details, please refer to the front-end code performance optimization tools you need to master

Flash and Ajax have their own advantages and disadvantages. How to choose between them in use?

Flash ajax contrast:
	Flash Suitable for processing multimedia, vector graphics and accessing machines; yes CSS,Insufficient text processing, not easy to be searched.
	Ajax yes CSS,Text support is very good, support search; Insufficient access to multimedia, vector graphics and machines.
	Common points: no refresh message delivery with the server, offline and online status of users, and operation DOM

Please explain the homology strategy of JavaScript.

concept:The same origin policy is client script (especially Javascript)Important safety metrics. It first came from Netscape Navigator2.0,The purpose is to prevent a document or script from being loaded from multiple different sources.

The same origin policy here refers to the same protocol, domain name and port. The same origin policy is a security protocol.
A script can only read the properties of windows and documents from the same source.

Why should there be homology restriction?

Let's give an example: for example, a hacker program that uses Iframe Embed the real bank login page into his page. When you log in with your real user name and password, his page can be accessed through Javascript Read into your form input So that the user name and password can be easily obtained.

What is "use strict"? What are the advantages and disadvantages of using it?

ECMAscript 5 Added a second operation mode: "strict mode"( strict mode). As the name suggests, this model makes Javascript Operate under more stringent conditions.

The purpose of establishing "strict mode" mainly includes the following:
 1. eliminate Javascript Some unreasonable and imprecise parts of grammar reduce some strange behaviors;
 2. Eliminate some unsafe places in code operation and ensure the safety of code operation;
 3. Improve the efficiency of the compiler and increase the running speed;
 4. For future versions Javascript Pave the way.
Note: tested IE6,7,8,9 Strict mode is not supported.

Disadvantages:
	Current website JS Will be compressed. Some files use strict mode, while others do not. At this time, these files, which were originally in strict mode, were deleted merge After, the string goes to the middle of the file. Instead of indicating the strict mode, it wastes bytes after compression.

The difference between GET and POST, when to use POST?

	GET: Generally used for information acquisition and use URL Transfer parameters also limit the number of messages sent, usually 2000 characters
    POST: There are no restrictions on the information sent to the server.

    GET The method needs to be used Request.QueryString To get the value of the variable, and POST Way through Request.Form To get the value of the variable,
    in other words Get Is to pass the value through the address bar, and Post The value is transferred by submitting a form.

However, in the following cases, please use POST Request:
 1. Cannot use cache file (update file or database on server)
 2. Send a large amount of data to the server( POST (no data limit)
 3. When sending user input containing unknown characters, POST than GET More stable and reliable

Where will css blocking occur and where will js blocking occur?

js Blocking feature: all browsers are downloading JS It will prevent all other activities, such as the download of other resources, the presentation of content and so on. until JS After downloading, parsing and executing, continue to download other resources in parallel and present the content. In order to improve the user experience, the new generation of browsers support parallel download JS,however JS Downloading will still block the downloading of other resources (e.g.Pictures, css Documents, etc.).

Because the browser in order to prevent JS modify DOM The tree needs to be rebuilt DOM Tree, so it will block other downloads and rendering.

embed JS Will block the rendering of all content, while the external JS It will only block the display of subsequent content, and both methods will block the download of subsequent resources. In other words, external styles will not block the loading of external scripts, but will block the execution of external scripts.

CSS How could it block the load? CSS It could have been downloaded in parallel. Under what circumstances will blocking load occur(During the test observation, IE6 lower CSS (all blocking loads)

When CSS Followed by embedded JS When the time comes, it's time CSS It will block the subsequent resource download. And when you embed JS put to CSS Before, there will be no blocking.

Root cause: because the browser will maintain html in css and js The order in which the stylesheet must be embedded JS Load and parse before execution. And embedded JS It will block the subsequent resource loading, so it will appear above CSS Blocking download.

embed JS Where should I put it?
 1. Put it at the bottom. Although placing it at the bottom will still block all rendering, it will not block resource download.
 2. If embedded JS Put on head Please insert JS Put on CSS Head.
 3. use defer(Only support IE)
 4. Do not embed JS In the long run function called, if it is necessary to use, you can use`setTimeout`To call

How to load Javascript without blocking

 1. Place the script at the bottom.<link>Or put it in head In order to ensure that js Before loading, the normally displayed page can be loaded.<script>Label on</body>front.
 2. Group scripts: due to each<script>The page parsing process is blocked during tag downloading, so the number of pages is limited<script>Totals can also improve performance. For inline and external scripts.
 3. Non blocking script: wait until the page is loaded js code. That is, in window.onload Start downloading the code after the event is issued.
	(1)defer Properties: support IE4 and fierfox3.5 Higher browser version
	(2)Dynamic script elements: Document Object Model( DOM)Allow you to use js Dynamic creation HTML Almost all of the document content. The code is as follows:
	<script>
		var script=document.createElement("script");
		script.type="text/javascript";
		script.src="file.js";
		document.getElementsByTagName("head")[0].appendChild(script);
	</script>
	The key point of this technology is that no matter where the download is started, the file download and operation will not block other page processing processes. Even in head Inside (except for downloading files) http Link).

Closure related issues?

For details, see: detailed explanation js closure

js event handler problem?

For details, see: JavaScript ***

What does eval do?

Its function is to parse the corresponding string into JS Code and run;
Use should be avoided eval,Unsafe, very performance consuming (2 times, once resolved to js Statement, executed at one time).

JavaScript prototype, prototype chain? What are the characteristics?

*  The prototype object is also an ordinary object. It is an implicit object __proto__ Property, the prototype may also have its own prototype. If the prototype of a prototype object is not null If so, we call it prototype chain.
*  A prototype chain is a (finite) chain of objects that are used to inherit and share attributes.

What is the difference between event mechanism, IE and Firefox? How to prevent bubbling?

 1. An operation in a web page (some operations correspond to multiple events). For example, when we click a button, an event will be generated. Can be JavaScript Detected behavior.
 2. Event handling mechanism: IE Is the event bubbling firefox At the same time, it supports two event models: capture event and bubble event.;
 3.  ev.stopPropagation();Pay attention to the old ie Method of ev.cancelBubble = true;

What is ajax? ajax interaction model? What is the difference between synchronous and asynchronous? How to solve cross domain problems?

For details, see: JavaScript *** Ajax and Http Status word
 1. Through asynchronous mode, the user experience is improved
 2. It optimizes the transmission between browser and server, reduces unnecessary data round-trip, and reduces bandwidth occupation
 3. Ajax Running on the client side, it undertakes part of the work originally undertaken by the server, reducing the server load under a large number of users.
 4. Ajax What is the biggest feature of.
	Ajax Dynamic non refresh (local refresh) can be realized
	readyState Attribute status has 5 values: 0=Uninitialized, 1=Start 2=Send, 3=Receive, 4=complete

ajax Disadvantages of
 1. ajax Browser not supported back Button.
 2. safety problem AJAX The details of the interaction with the server are exposed.
 3. Support for search engines is relatively weak.
 4. It destroys the exception mechanism of the program.
 5. Not easy to debug.
Cross domain: jsonp, iframe,window.name,window.postMessage,Set up proxy page on server

Deep cloning of js objects

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

What is the difference between AMD and CMD specifications?

For details, see: detailed explanation JavaScript Modular development

Understanding of website reconstruction?

Website reconstruction: the behavior of simplifying the structure and adding readability without changing the external behavior, while maintaining consistency at the front end of the website. In other words, it is not changing UI In this case, the website should be optimized to maintain consistency while expanding UI. 

For traditional websites, refactoring is usually:

form(table)Layout changed to DIV+CSS
 Make the front end of the website compatible with modern browsers(For non-conforming CSS,If right IE6 effective)
Optimization of mobile platform
 For SEO Optimize
 Aspects that should be considered in deep-seated website reconstruction

Reduce coupling between codes
 Keep your code flexible
 Write code in strict accordance with the specifications
 Design scalable API
 Replace the old framework and language(as VB)
Enhance user experience
 Generally speaking, the optimization of speed is also included in refactoring

compress JS,CSS,image Other front-end resources(It is usually solved by the server)
Program performance optimization(Such as data reading and writing)
use CDN To speed up resource loading
 about JS DOM Optimization of
HTTP Server's file cache

How to obtain UA?

<script> 
    function whatBrowser() {  
        document.Browser.Name.value=navigator.appName;  
        document.Browser.Version.value=navigator.appVersion;  
        document.Browser.Code.value=navigator.appCodeName;  
        document.Browser.Agent.value=navigator.userAgent;  
    }  
</script>

js array de duplication

Here are three ways to remove the duplicate of an array:

Array.prototype.unique1 = function () {
  var n = []; //A new temporary array
  for (var i = 0; i < this.length; i++) //Traverse the current array
  {
    //If the i of the current array has been saved into the temporary array, skip,
    //Otherwise, push the current item into the temporary array
    if (n.indexOf(this[i]) == -1) n.push(this[i]);
  }
  return n;
}

Array.prototype.unique2 = function()
{
    var n = {},r=[]; //n is the hash table and r is the temporary array
    for(var i = 0; i < this.length; i++) //Traverse the current array
    {
        if (!n[this[i]]) //If there is no current item in the hash table
        {
            n[this[i]] = true; //Store in hash table
            r.push(this[i]); //push the current item of the current array into the temporary array
        }
    }
    return r;
}

Array.prototype.unique3 = function()
{
    var n = [this[0]]; //Result array
    for(var i = 1; i < this.length; i++) //Traverse from the second item
    {
        //If the i-th item of the current array does not appear at I for the first time in the current array,
        //Then it means item i is repeated and ignored. Otherwise, it is stored in the result array
        if (this.indexOf(this[i]) == i) n.push(this[i]);
    }
    return n;
}

HTTP status code

100  Continue  Continue, usually sending post The request was sent http header After that, the server will return this information, indicating confirmation, and then send specific parameter information
200  OK   Normal return information
201  Created  The request succeeded and the server created a new resource
202  Accepted  The server has accepted the request but has not yet processed it
301  Moved Permanently  The requested page has been permanently moved to a new location.
302 Found  Temporary redirection.
303 See Other  Temporary redirection and always use GET Request new URI. 
304  Not Modified  The requested page has not been modified since the last request.

400 Bad Request  The server cannot understand the format of the request, and the client should not try to initiate the request with the same content again.
401 Unauthorized  The request is not authorized.
403 Forbidden  Access is prohibited.
404 Not Found  Can't find how to communicate with URI Matching resources.

500 Internal Server Error  The most common server-side error.
503 Service Unavailable The server side is temporarily unable to process the request (possibly overload or maintenance).

js operation to get and set cookie s

//Create cookie
function setCookie(name, value, expires, path, domain, secure) {
    var cookieText = encodeURIComponent(name) + '=' + encodeURIComponent(value);
    if (expires instanceof Date) {
        cookieText += '; expires=' + expires;
    }
    if (path) {
        cookieText += '; expires=' + expires;
    }
    if (domain) {
        cookieText += '; domain=' + domain;
    }
    if (secure) {
        cookieText += '; secure';
    }
    document.cookie = cookieText;
}

//Get cookie
function getCookie(name) {
    var cookieName = encodeURIComponent(name) + '=';
    var cookieStart = document.cookie.indexOf(cookieName);
    var cookieValue = null;
    if (cookieStart > -1) {
        var cookieEnd = document.cookie.indexOf(';', cookieStart);
        if (cookieEnd == -1) {
            cookieEnd = document.cookie.length;
        }
        cookieValue = decodeURIComponent(document.cookie.substring(cookieStart + cookieName.length, cookieEnd));
    }
    return cookieValue;
}

//delete cookie 
function unsetCookie(name) {
    document.cookie = name + "= ; expires=" + new Date(0);
}

Talk about the triple handshake strategy of TCP transmission

In order to deliver the data to the target accurately, TCP The protocol adopts the strategy of three handshakes. use TCP After the protocol sends out the data packet, TCP It will not ignore the situation after transmission. It will certainly confirm whether it has been successfully delivered to the other party. Used during handshake TCP Sign of: SYN and ACK. 
The sender sends a band first SYN Mark the packet to the other party. After receiving, the receiving end returns a message with SYN/ACK Marked data package to convey confirmation information. Finally, the sender sends back another band ACK The packet marked represents the end of the "handshake"
If there is an unexplained interruption at some stage in the handshake process, TCP The protocol sends the same packets again in the same order.

Tell me about your understanding of Promise

according to Promise/A+ The definition of, Promise There are four states:
	* pending: Initial state, wrong fulfilled or rejected.
	* fulfilled: Successful operation.
	* rejected: Failed operation.
	* settled: Promise Has been fulfilled or rejected,And not pending
	In addition, fulfilled And rejected Together settled. 

Promise Object is used to delay(deferred) And asynchronous(asynchronous ) calculation.

Promise Constructor for:
	Construct a Promise,The basic usage is as follows:
		var promise = new Promise(function(resolve, reject) {
		    if (...) {  // succeed
		        resolve(result);
		    } else {   // fails
		        reject(Error(errMessage));
		    }
		});
		Promise Instance ownership then Method (with then Method, usually called thenable). 
		Its usage is as follows:		
			promise.then(onFulfilled, onRejected)
			Receive two functions as parameters, one in fulfilled When called, one in rejected When called, the received parameter is future,onFulfilled corresponding resolve, onRejected corresponding reject. 

Javascript garbage collection method

 1. Mark clear( mark and sweep)
	This is JavaScript The most common garbage collection method is that when a variable enters the execution environment, such as declaring a variable in a function, the garbage collector marks it as "entering the environment", and when the variable leaves the environment (the end of function execution), it marks it as "leaving the environment".
	The garbage collector will mark all variables stored in memory when running, and then remove the variables in the environment and the variables referenced by the variables in the environment (closures). After these are completed, the variables still marked are the variables to be deleted
	
 2. Reference count(reference counting)
	In lower version IE Memory leaks often occur in, often because it uses reference counting for garbage collection. The strategy of reference counting is to track and record the number of times each value is used. When a variable is declared and a reference type is assigned to the variable, the number of references to the value will be increased by 1. If the value of the variable becomes another, the number of references to the value will be reduced by 1. When the number of references to the value becomes 0, it means that no variable is in use, This value cannot be accessed, so the space occupied by it can be recycled, so the garbage collector will clean up the space occupied by the value with reference times of 0 when running.

	stay IE Although in JavaScript Object is garbage collected by mark removal, but BOM And DOM Objects are garbage collected by reference counting, that is, as long as it involves BOM and DOM There will be a circular reference problem.

 3. Talk about performance optimization
	Code level: avoid using css Expression, avoid using advanced selectors and universal selectors.
	Cache utilization: cache Ajax,use CDN,Use external js and css Files for caching, adding Expires Header, server configuration Etag,reduce DNS Find, etc
	Number of requests: merge styles and scripts, using css Picture Wizard: picture resources outside the initial first screen are loaded on demand, and static resources are loaded late.
	Request bandwidth: compressed file, on GZIP,

 4. Mobile terminal performance optimization
	Try to use css3 Animation, turn on hardware acceleration. Appropriate use touch Event substitution click event. Avoid using css3 Gradient shadow effect.
	Use as little as possible box-shadow And gradients. box-shadow And gradients It is often the performance killer of the page

What is Etag?

When the browser downloads components, they are stored in the browser cache. If you need to get the same component again, the browser will check the cache time of the component. If it has expired, the browser will send a condition GET The request is sent to the server. If the server determines that the cache is still valid, it sends a 304 response to tell the browser that the cache component can be reused.

So what does the server judge whether the cache is still valid?There are two ways to answer, one is the above-mentioned ETag,The other is based on Last-Modified

 1. Expires and Cache-Control	
	Expires The clocks of the client and server are required to be strictly synchronized. HTTP1.1 introduce Cache-Control To overcome Expires Head restrictions. If max-age and Expires Appears simultaneously, then max-age Have higher priority.

	Cache-Control: no-cache, private, max-age=0
	ETag: abcde
	Expires: Thu, 15 Apr 2014 20:00:00 GMT
	Pragma: private
	Last-Modified: $now // RFC1123 format
	

 2. The difference between stack and queue?
	The insertion and deletion operations of the stack are carried out at one end, while the operation of the queue is carried out at both ends.
	Queue FIFO, stack FIFO.
	The stack only allows insertion and deletion at the end of the table, while the queue only allows insertion at the end of the table and deletion at the head 

 3. What is the difference between stack and heap?
	Stack area( stack)—   It is automatically allocated and released by the compiler to store the parameter values of the function and the values of local variables.
	Heap area( heap)   —   Generally, it is allocated and released by the programmer. If the programmer does not release it, it may be released by the programmer at the end of the program OS Recycling.
	Heap (data structure): heap can be regarded as a tree, such as heap sorting;
	Stack (data structure): a first in and last out data structure. 

 4. about Http 2.0 How much do you know?
	HTTP/2 Introduced "service push"( serverpush)"It allows the server to actively send data to the client cache before the client needs data, so as to improve performance.
	HTTP/2 Provide more encryption support
	HTTP/2 Using multiplexing technology, multiple messages are allowed to cross at the same time on one connection.
	It increases head compression( header compression),Therefore, even if the request is very small, its request and response are very complex header Will only occupy a small proportion of bandwidth.

Keywords: Javascript css3 html

Added by wrequed on Fri, 11 Feb 2022 19:29:08 +0200