Summary of some common interview questions, simple version, hope to just graduate to find a job partners useful

HTML

1. What happens when you enter the url and press Enter to see the web page?

The answer:

1. Domain name resolution 2. Initiate TCP three-way handshake (ACK ACK+SYN ACK)x 3. Sending an HTTP request after establishing a TCP connection 4. The server responds to the HTTP request and the browser obtains the HTML code 5. The browser parses the HTML code and requests resources in the HTML code. 6. The browser renders the page to the userCopy the code

2, Doctype function? What is the difference between standard mode and compatible mode?

The answer:

1. <! The DOCTYPE> declaration is located on the first line of the HTML document, before the < HTML > tag. Tell the browser's parser what document to use to parse the document. 2. Standard mode of typesetting and JS mode of operation are based on the highest standards supported by the browser. 3. In compatibility mode, pages are displayed in a loosely backward compatible manner, mimicking the behavior of older browsers in case the site doesn't work. 4. A non-existent or improperly formatted DOCTYPE will result in the document being rendered in promiscuous mode.Copy the code

3. Why does HTML5 only need to write?

The answer:

1. HTML5 is not based on SGML, so there is no need to reference DTDS, but docType is needed to regulate browser behavior (let browsers behave the way they should); 2. HTML4.01 is based on SGML, so you need to reference a DTD to tell the browser what document type the document is using.Copy the code

4. How many docTypes do you know?

The answer:

1. Tags can declare three DTD types, representing strict versions, transitional versions, and frame-based HTML documents. HTML 4.01 specifies three document types: Strict, Transitional, and Frameset. XHTML 1.0 specifies three XML document types: Strict, Transitional, and Frameset. 4. Standards mode (also known as strict rendering mode) is used to render web pages that comply with the latest Standards. 5. Quirks (loosely rendered or compatible) are used to render web pages designed for traditional browsers.Copy the code

5. HTML vs. XHTML — What’s the difference?

The answer:

1. XHTML elements must be properly nested. 2. XHTML elements must be closed. 3. The label name must be lowercase. 4. XHTML documents must have root elements.Copy the code

6. What are the inline elements? What are block-level elements? What are the void elements?

The answer:

First of all, according to the CSS specification, every element has a display attribute, which determines the type of the element. Each element has a default display value. For example, if the default display value of div is "block", it is a "block-level" element. The default value of the span display attribute is "inline", which is the "inline" element. A b span img input select strong; 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 metaCopy the code

7. What is the difference between using link and @import when importing styles?

The answer:

1. Link is an XHTML tag. In addition to loading CSS, it can also be used to define RSS, rel connection attributes, etc. @import is provided by CSS and can only be used to load CSS; 2. When the page is loaded, link is loaded at the same time, and the CSS referenced by @import waits until the page is loaded. 3. Import is proposed by CSS2.1, which can only be recognized in IE5, while link is XHTML tag, which has no compatibility problems;Copy the code

Introduce your understanding of browser kernel?

The answer:

1. It is mainly divided into two parts: layout Engineer or Rendering Engine and JS Engine. 2. Rendering engine: it is responsible for taking the content of the web page (HTML, XML, images, etc.), organizing the information (such as adding CSS, etc.), and calculating the display of the web page, and then output to the monitor or printer. The syntax of the web page will be interpreted differently depending on the browser kernel, so the rendering effect will be different. All Web browsers, E-mail clients, and other applications that need to edit and display web content require a kernel. 3. JS engine: parsing and executing javascript to achieve the dynamic effect of web pages. 4. At the beginning, there was no clear distinction between rendering engine and JS engine. Later, JS engine became more and more independent, and the kernel tended to refer only to rendering engine.Copy the code

9. What is the kernel of the browser?

The answer:

The Internet Explorer kernel is Trident, Mozilla kernel is Gecko, Chrome kernel is Blink (a branch of WebKit), Opera kernel is Presto, now Blink, and Safari kernel is WebKit.Copy the code

10. Semantic understanding?

The answer:

1. Do the right thing with the right labels! 2. Semantic HTML is to make the content of the page structured, easy to browser, search engine parsing; 3. Display in a document format without style CCS, and it is easy to read. 4. Search engine crawlers rely on tags to determine the context and weight of each keyword, which is conducive to SEO. 5. Make it easier for people to read the source code to divide the site into blocks for easy reading and maintenance.Copy the code

What is graceful degradation and progressive enhancement?

The answer:

1. Progressive enhancement: Build the page for low-version browsers to ensure the most basic functions, and then improve the effect, interaction and additional functions for advanced browsers to achieve better user experience. 2. Degrade Graceful graceful Degradation: Build full functionality from the start and then make it compatible with older browsers. Difference: 3. Elegant downgrading starts with a complex status quo and tries to reduce the supply of user experience 4. Progressive enhancement starts with a very basic, working version and expands to meet the needs of future environments. Downgrading (functional decay) means looking backwards; Incremental enhancement means looking forward while keeping its roots in a safe zoneCopy the code

12. Can you talk about the disadvantages of cookies?

The answer:

1. There is a limit to the number of cookies that can be generated for each specific domain, and any additional cookies will be truncated: 20 cookies for IE6 and later versions, up to 50 cookies for IE7 and later versions. Chrome and Safari do not set a hard limit. 2. Internet Explorer and Opera clean up the least recently used cookies, while Firefox cleans cookies randomly. 3. The maximum value of cookie is about 4096 bytes. For compatibility, the maximum value cannot be 4095 bytes. 4. Security issues. If the cookie is intercepted, that person can get all session information. Even encryption is useless, because the interceptor does not need to know the meaning of the cookie, as long as he forwards the cookie can achieve the goal. 5. Some states cannot be saved on the client. For example, to prevent forms from being submitted repeatedly, we need to save a counter on the server side. If we keep this counter on the client side, it does nothing. 6. IE provides a way to store persistent userdata, called userdata, which has been supported since IE5.0. Each domain name contains a maximum of 128 KB data, and each domain name contains a maximum of 1 MB data. This persistent data is stored in the cache and persists if the cache is not cleaned. 7. Advantages: High scalability and availability: Control the size of session objects stored in cookies through good programming. Through encryption and secure transmission technology (SSL), reduce the possibility of cookie cracking. Store only insensitive data in cookies, so there is no significant loss if stolen. Controls the lifetime of cookies so that they do not last forever. The thief probably got hold of an expired cookie.Copy the code

13. What is HTML5 offline storage, how it works, and how to use it?

The answer:

1. When the user is not connected to the Internet, the user can access the site or application normally. When the user is connected to the Internet, the cache file on the user machine is updated. 2. Principle: When online, the browser finds the MANIFEST attribute in the HTML header, and it will request the MANIFEST file. If it is the first time to access the APP, the browser will download the corresponding resources according to the contents of the MANIFEST file and store them offline. If the app has already been accessed and the resource has been stored offline, the browser will load the page using the offline resource. Then the browser will compare the new manifest file with the old manifest file. If the file has not changed, nothing will be done. The resources in the file are then re-downloaded and stored offline.  offline case, the browser uses the offline stored resource directly. 3. How to use it: Add a manifest attribute to the page header as shown below; The cache. Manifest file is written to store offline resources; CACHE MANIFEST #v0.11 CACHE: js/app.js CSS /style. CSS NETWORK: resourse/logo.png FALLBACK: / /offline. HTML In offline state, operate window.applicationCache to implement requirements.Copy the code

14, What is Web storage?

The answer:

1. LocalStorage: Stores data for a long time. Data is not lost after the browser is closed. 2. SessionStorage: Data is automatically deleted after the browser is closed; 3. LocalStorage and sessionStorage have the same operation methods, such as setItem, getItem, and removeItem.Copy the code

15, The difference between Web storage and cookie?

The answer:

1. The concept of Web Storage is similar to cookie, but the difference is that it is designed for larger Storage capacity. Cookie size is limited, and cookies are sent every time you request a new page, which wastes bandwidth. 2. In addition, the cookie scope must be specified and cannot be invoked across domains. With setItem (3) the Web Storage, the getItem, removeItem, methods of the clear, don't like cookies need to encapsulate setCookie front-end developer himself, getCookie; 4 but cookie is also can not or lack of: the role of cookie is to interact with the server, as part of the HTTP specification exists, and Web Storage is only in order to local "Storage" data and born; 5. Browsers in addition to IE7 and the following does not support, other standard browsers are fully supported (IE and FF need to run in the Web server), it is worth mentioning that IE is always good, such as IE7, IE6 userData is actually javascript local storage solution. Through simple code encapsulation can be unified to all browsers support Web storage.Copy the code

Please describe the difference between cookies, sessionStorage and localStorage.

The answer:

1. Cookie refers to the data (usually encrypted) stored on the Client Side of a user by a website to mark the user's identity. 2. Cookie data is always carried (even if it is not needed) in a same-origin HTTP request, that is, passed back and forth between the browser and the server. 3. SessionStorage and localStorage do not automatically send data to the server and store data locally. 4. SessionStorage and localStorage have more rich and easy-to-use interfaces; 5. Independent storage space for sessionStorage and localStorage. Storage size: 6. Cookie data size cannot exceed 4K; SessionStorage and localStorage, while also limited in size, are much larger than cookies, reaching 5M or more. 7. LocalStorage stores persistent data. Data is not lost after the browser is closed unless the data is deleted actively. 8. SessionStorage data is automatically deleted after the current browser window is closed. 9. Cookie Settings remain valid until expiration time, even if the window or browser is closed 10. Therefore, I suggest: Store important information such as login information as SESSION; Other information can be stored in cookies if neededCopy the code

17. What are the disadvantages of iframe?

The answer:

1. Iframe will block the Onload event on the main page; 2. The iframe and the main page share the connection pool, and the browser has restrictions on connections to the same domain, which affects the parallel loading of pages. 3. These two disadvantages need to be considered before using iframe. If you need to use an iframe, it is best to use javascript to dynamically add the SRC attribute value to the iframe to avoid these two problems.Copy the code

18. How do HTML5 forms turn off auto-complete?

The answer:

Set autoComplete =off for unprompted forms or the next input.Copy the code

19. How to achieve communication between multiple tabs in the browser?

The answer:

1. WebSocket, SharedWorker; 2. You can also invoke local storage modes such as localStorge and cookies. 3. For example, when localStorge is added, modified or deleted in another browsing context, it will trigger an event and control its value to carry out page information communication by listening to the event; 4. Note quirks: Safari raises QuotaExceededError when setting localStorge in traceless mode.Copy the code

20. How is webSocket compatible with low browsers?

The answer:

Adobe Flash Socket, ActiveX HTMLFile (IE), XHR based on Multipart encoding, XHR based on long pollingCopy the code

21. What are the new features and elements removed from HTML5? How to deal with the browser compatibility of HTML5 new tags? How to distinguish HTML from HTML5?

The answer:

1. HTML5 is no longer a subset of SGML, mainly about the addition of graphics, location, storage, multitasking, etc. : Canvas 
 Video and audio elements for media playback 
 Local offline storage of more semantic content elements such as article, footer, header, nav, section
 form controls, Calendar, Date, time, email, URL, search
 New technologies Webworker, websockt, Geolocation 2. Elements removed 
 Pure elements: Basefont, Big, Center, font, S, Strike, TT, u; 
 Elements that negatively affect usability: Frame, Frameset, Noframes; 
 3. IE8/IE7/IE6 supports tags generated by the document.createElement method. You can use this feature to enable these browsers to support new HTML5 tags. Of course, the best way is to directly use mature framework, the most used is html5shiv framework 
 <! - > [if lt IE 9] college < script > SRC = "html5shiv. Js" < / script > college <! [endif]-->
 4. How to distinguish: DOCTYPE declaration \ new structure element \ function elementCopy the code

22. What are the disadvantages of table?

The answer:

1. Too deep nesting, such as table>tr> TD >h3, will make it difficult for search engines to read, and the most immediate loss is to greatly increase the amount of redundant code. Tr border = "border"; tr border = "border"; tr border = "border" The code is bloated, and when the table is used in the table, the code will appear abnormal confusion. 4. Colspan and RowSpan are chaotic, and their frequent use can cause the entire document to be out of order when used for layout. 5. Table requires multiple computations to determine the attributes of its nodes in the rendering tree, usually taking three times as long as the equivalent element. 6. Not semantic enoughCopy the code

What is the difference between SRC and href?

The answer:

1. SRC replaces the current element; Href is used to establish a link between the current document and the referenced resource. Href = Hypertext Reference; href = Hypertext Reference; href = Hypertext Reference; Copy the code

CSS

1. What is the box model of CSS?

The answer:

1. There are two kinds, IE box model, standard W3C box model; 2. Content (including border and padding) and margin of IE box model; 3. Box model: Content, padding, margin, border.Copy the code

2. Style Inheritance?

The answer:

Font size font family color; 2. Non-inheritable styles: border padding margin width height, etc.Copy the code

3. The priority of the selector?

The answer:

1.! Important > id > class > tag 2. Important has a higher priority than inlineCopy the code

4, how to design a full screen product word layout?

The answer:

Simple way: The div above is 100% wide, the div below is 50% wide, and then use float or inline to make them line freeCopy the code

5. Why should CSS styles be initialized?

The answer:

Because of browser compatibility issues, different browsers have different default values for some tags. If CSS is not initialized, the page display will often be different between browsers.Copy the code

6. Understanding of BFC specifications?

The answer:

1. (A concept in the W3C CSS 2.1 specification that determines how an element locates its content and how it relates and interacts with other elements.) 2. A page is composed of several boxes. The type of the Box is determined by the element type and display attribute. 3. Different types of boxes will involve different Formatting contexts, so elements in boxes will be rendered in different ways, that is, elements inside and outside the BFC will not affect each other.Copy the code

7. If you need to write animation manually, what is the minimum time interval you think? Why?

The answer:

The default frequency of most monitors is 60Hz, which means 60 refreshes per second, so the minimum interval is theoretically 1/60 * 1000ms = 16.7msCopy the code

8, Position is relative and absolute.

The answer:

Relative absolute Fixed static inherit 1. Absolute: Generates an absolutely positioned element relative to the first parent element whose value is not static. 2. Fixed (old IE does not support) : Generates an absolute location element that is positioned relative to the browser window. 3. Relative: Generates elements that are positioned relative to their normal position. 4. Static: default value. Without positioning, the element appears in the normal stream (ignoring the top, bottom, left, right Z-index declarations). Inherit: Specify that the value of the position property is inherited from the parent element.Copy the code

9. What is the principle behind creating a triangle with pure CSS?

The answer:

#demo {width: 0; height: 0; border-width: 20px; border-style: solid; border-color: transparent transparent red transparent; }Copy the code

10, please list how many ways (at least two ways) you can clear float?

The answer:

Floats float above normal flow, like clouds, but only from left to right. It is this property that causes the inside of the box to show a height of zero (height collapse) because there are no other normal flow elements. <div style="clear:both"></div> 2. Use the BR tag and its own HTML attributes, such as <br clear="all" /> 3. The parent element sets overflow: hidden; In IE6 you also need to trigger hasLayout, such as Zoom: 1; The parent element sets overflow: auto; IE6 also needs to trigger hasLayout 5. The parent element is also set to float 6. Display :table 7. Use :after pseudo-element; Since Internet Explorer 6-7 does not support :after, use Zoom :1 to trigger hasLayout.Copy the code

11. How many ways can you hide elements?

The answer:

1. The visibility: hidden; This attribute simply hides an element, but the space occupied by the element still exists; 2. The opacity: 0; A CSS3 property, set to 0, makes an element completely transparent, creating the same effect as visibility. Compared to visibility, it can be transformed by transition and animate; 3. Position: absolute; Take the element out of the flow of the document and place it above the normal document, giving it a large left negative position so that the element is outside of the visible area. 4. Display: none; Elements become invisible and no longer take up space in the document; 5. The transform: scale (0); If you set an element to infinitesimal, the element will not be visible. The element will remain where it was; 6. HTML5's hidden property; Hidden property effect and display: None; Again, this property is used to record the state of an element; 7. height: 0; Overflow: hidden; Shrink the element to 0 vertically, making the element disappear. This technique works as long as the element has no visible border; 8. The filter: the blur (0); An element "disappears" from the page by setting its ambiguity to 0.Copy the code

What is the difference between CSS pseudo-classes and CSS pseudo-objects?

The answer:

1. CSS introduced the concept of pseudo classes and pseudo elements to describe something that cannot be described in existing CSS; The fundamental difference is whether they create new elements (abstractions); 2. Pseudo-classes: originally used to represent the dynamic state of some elements, the CSS2 standard expanded the concept to include all logically existing "ghost" categories that do not need to be identified in the document tree; 3. Pseudo-object: Represents a child of an element that exists logically but does not actually exist in the document tree.Copy the code

13, Please write a variety of contour layout?

The answer:

1. False contour column: use the background image to lay the Y-axis on the parent element of the column, so as to realize a false contour column; 2. Use a separate background color for container divs (fixed layout) (fluid layout) : use the maximum height in the <div> element to expand other <div> container heights; 3. Create a two-column contour layout with a border: use border-left, only two columns; 4. Use positive padding and negative margin hedging to create a multi-column layout. Use positive padding and negative padding and negative margin hedging to create a multi-column layout. 5. Use borders and position analog columns equal height: but cannot be used in multiple columns; 6. Imitation of high column effect such as table layout: Poor compatibility, cannot run properly in IE6-7.Copy the code

14. How to center block elements of variable width horizontally?

The answer:

1. Element_father{ float: left; /* Adjust content width */ position: relative; left: 50%; } Element_children{ position: relative; left: -50%; } 2. Use tablesCopy the code

15, how to achieve the left and right two column layout, left adaptive, right fixed width?

The answer:

Left adaptive outer wrap {width:100%; float:left; } left adaptive {margin-right:width} right fixed {width+float:right+margin-left:-width; }Copy the code

16. Px and EM are often used in CSS styles. What are the advantages and disadvantages of them?

The answer:

1. Px is a unit of relative length, relative to the screen resolution of a display. 2. Em is a unit of relative length, relative to the font size of the text in the current object. 3. Font defined by PX cannot be enlarged by browser font. 4. The value of em is not fixed, it inherits the font size of the parent element, 1 ÷ the font size of the parent element × the pixel value to be converted = em value.Copy the code

17. What is FOUC (unstyled content flicker)? How do you avoid FOUC?

The answer:

If you use the import method to import the CSS, some pages will have a strange phenomenon in IE on Windows. This phenomenon is called Flash of Unstyled Content, or FOUC for short. How it works: When the stylesheet loads later than the structural HTML, the page stops rendering when it is loaded into the stylesheet. After the stylesheet is downloaded and parsed, the page is rerendered, and the screen briefly flickers. Workaround: Use the LINK tag to place the stylesheet in the document HEAD.Copy the code

18, What is the difference between the three assignment methods? (with units, pure figures, percentages)?

The answer:

1. Unit: PX is not counted; 2. Em uses the font size of its parent element as a reference to calculate its own line height; 3. Pure numbers: pass the ratio to the offspring, for example, if the parent line height is 1.5 and the child element font is 18px, then the child element line height is 1.5*18=27px; 4. Percentage: Pass the calculated value to future generations.Copy the code

19, : Link, :visited, :hover, :active execution order is what?

The answer:

L-v-h-a, L (Link)ov(visited)e H (hover) A (active)te, namely, love and hate two words to summarizeCopy the code

20. Sprite diagram principle?

The answer:

CSS Sprite is a popular way of processing web images, that is, all fragmentary web background images are integrated together, which can effectively reduce the number of HTTP requests for images, and do not need to load fragmentary background images for many times. So reasonable use of it can effectively improve the loading speed of web pages. 2. The CSS uses the combination of "background-image", "background-repeat", and "background-position" to locate the background.Copy the code

Common Compatibility Problems

1. Png24-bit images appear in the background of iE6.

Solution:

Make the image in PNG8 format.Copy the code

2, browser default margin and padding are different?

Solution:

Do a style reset.Copy the code

3, IE6 bilateral distance bug?

Cause: After the block property tag float, there is a margin situation in ie6 showing margin larger than set.Copy the code

Solution:

Add -- _display:inline; Convert it to an inline property. (_ This symbol is recognized only by IE6)
.Copy the code

4. Min-height does not work in IE6.

Solution:

{ width: auto; height: auto; min-width: 80px; min-height: 35px; }Copy the code

While IE uses filter:Alpha(Opacity=60), other mainstream browsers use Opacity :0.6.

6. Z-index problem.

Solutions:

1. The hierarchy of IE6 and ie7 (hybrid mode IE8) depends not only on itself, but also on whether the parent element is powerful: When the position attribute of the parent element is relative or absolute, the absolute attribute of the child element is relative to the parent element. In IE6 hierarchies sometimes behave not by the z-index of the child elements, but by the Z-index of their parent elements. 2. Z-index is invalid when the parent element is set to relative and the child element is set to float. So change relative to absolute or remove float.Copy the code

JavaScript

1. How to use strict mode?

The answer:

"use strict";
Copy the code

2, Introduce the basic data types of JS.

The answer:

Number, String, Boolean, Object, Undefined, Null, add SymbolCopy the code

3. What built-in objects does JS have?

The answer:

1. Object is the parent of all objects in JavaScript; 2. Data encapsulation class objects: Object, Array, Boolean, Number, and String; Other objects: Function, Arguments, Math, Date, RegExp, Error. 4ate Array function argument math string boolean errorCopy the code

4. What are some basic rules for writing JavaScript?

The answer:

1. Do not declare multiple variables on the same line. 2. Please use ===/! == to compare true/false or numeric values 3. Use object literals instead of new Array 4. Do not use global functions. 5. Switch statements must have default branches 6. Functions should not sometimes return a value and sometimes not return a value. If statements must use curly braces 9. Variables in for-in loops should be explicitly scoped with the var keyword to avoid scope contamination.Copy the code

Null, undefined difference?

The answer:

1. Null is an object representing "none" and is 0 when converted to a value. Undefined is a primitive value for "none", which is NaN when converted to a value. 2. If the declared variable is not initialized, the default value of the variable is undefined. Null is used to indicate that an object does not yet exist, and is often used to indicate that a function attempts to return an object that does not exist. 3. Undefined means "missing value", that is, there should be a value here, but it is not defined yet. Typically, a variable that is declared but not assigned is undefined. When the function is called, the argument that should be provided is not provided, which is equal to undefined. The object has no assigned attribute, the value of which is undefined. If the function returns no value, undefined is returned by default. 4. Null means "no object", that is, there should be no value. Typically: as arguments to a function, indicating that the function's arguments are not objects. As the end of the object prototype chain.Copy the code

What’s the difference between document.write and innerHTML?

The answer:

1. Document. Write Redraws only the entire page. 2Copy the code

7. What is your understanding of This object?

The answer:

1. This is a keyword of JS. The value of this will change depending on where the function is used. But the general rule is that this refers to the object on which the function is called. 2. This is the Global object. As a method call, then this is the object.Copy the code

8. What exactly does the new operator do?

The answer:

1. Create an empty object and the this variable references the object and inherits the prototype of the function. 2. Properties and methods are added to the object referenced by this. 3. The newly created object is referenced by this and returns this implicitly.Copy the code

9. What does Eval do?

The answer:

1. Its function is to parse the corresponding string into JS code and run it; 2. Eval should be avoided. It is unsafe and very expensive to use (2 times, once parsed into JS statements, once executed). Var obj =eval('('+ STR +')'); var obj =eval('('+ STR +')');Copy the code

What is a closure and why do you use it?

The answer:

1. Closures are a special kind of object. It consists of two parts: the function and the environment in which the function is created. 2. Closures can be understood simply as "a function defined inside a function." Closures are Bridges that connect the inside of a function to the outside of a function. 3. Closures are used primarily to design private methods and variables. The advantage of closures is that they can avoid the pollution of global variables, but the disadvantage is that closures will live in memory, which will increase the memory usage, and improper use will easily cause memory leaks. In JS, functions are closures, and only functions have the concept of scope.Copy the code

How does js determine an array?

The answer:

Select * from arr; select * from arr; select * from arr; select * from arr; Function isArrayFn(value){if (typeof array. isArray === "function") {return Array.isArray(value); }else{ return Object.prototype.toString.call(value) === "[object Array]"; // return obj.__proto__ === Array.prototype; }} 4, use the Object. The prototype. ToString, call () on the prototype chain operation Such as: Object. The prototype. ToString. Call ([]) = = = '[Object Array]' / / true. 5, using the Array isArray () such as: Array. IsArray ([)Copy the code

What is the difference between.call() and.apply()?

The answer:

Call (sub,3,1) == add(3,1); alert(4); Note: functions in js are actually objects, and Function names are references to Function objects. function add (a,b) { alert(a+b); } function sub (a,b) { alert(a-b); } the add. Call (sub, 3, 1);Copy the code

13. How does Javascript implement inheritance?

The answer:

Through prototypes and constructorsCopy the code

JavaScript prototype, prototype chain? What are the characteristics?

The answer:

Every object initializes a property inside of it, called prototype. When we access an object's property, if the property doesn't exist inside the object, the object will look for the property in Prototype, which in turn will have its own prototype. And so the search goes on and on, and that's what we call the prototype chain. Features: JavaScript objects are passed by reference, and each new object entity we create does not have a copy of its own prototype. When we modify the stereotype, the objects associated with it inherit the change. When we need a property, the Javascript engine looks to see if the property is present in the current Object, and if not, looks for the property in its Prototype Object, and so on, until it reaches the Object built-in Object.Copy the code

Javascript scope domain?

The answer:

Global functions cannot view the internal details of local functions, but local functions can view the function details on top of them, up to the global details. When you need to find a property or method from a local function, if the current scope is not found, the search will be traced back to the upper scope, all the way to the global function, this organization is the scope chain.Copy the code

16, How to determine whether an object belongs to a class?

The answer:

if(a instanceof Person){
           alert('yes');
}
Copy the code

17. In Javascript, there is a function that performs object lookup and never looks up the prototype. What is this function?

The answer:

HasOwnProperty: Determines whether an object has a property or object with the name you give it. Note, however, that this method does not check whether the property is present in the prototype chain of the object. The property must be a member of the object itself, for example:.object.hasownProperty (proName); Determine whether the proName name is a property or object of the object.Copy the code

18. Understanding of JSON?

The answer:

1. JSON(JavaScript Object Notation) is a lightweight data interchange format. It is based on a subset of JavaScript. The data format is simple, easy to read and write, and occupies little bandwidth. {"age":"12", "name":"back"}Copy the code

19. What is the difference between XML and JSON?

The answer:

1. Compared to XML, JSON data is smaller and faster to transfer. 2. The interaction between JSON and JavaScript is more convenient, easier to parse and handle, and better data interaction. 3. JSON is less descriptive of data than XML. 4. JSON is much faster than XML.Copy the code

20. What are the ways of JS lazy loading?

The answer:

Defer and Async, create the DOM dynamically (most used), and load JS asynchronously on demand.Copy the code

21. What are the methods of asynchronous loading?

The answer:

1. Defer, which only supports IE. 2. Async: 3Copy the code

22. Which operations cause memory leaks?

The answer:

1. A memory leak is any object that persists after you no longer own or need it. 2. 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 zero (no other object has ever referenced it), or the only references to the object are cyclic, then the object's memory is reclaimed. 3. Using a string instead of a function as the first argument to setTimeout causes a memory leak. 4. Closures, console logging, loops (a loop is created when two objects reference and retain each other)Copy the code

23. What is Ajax?

The answer:

Asynchronous Javascript And XML 1. Asynchronous transmission + JS + XML The so-called asynchronous, simply explained here is: when sending a request to the server, we do not have to wait for the result, but can do other things at the same time, until the result itself will follow up according to the Settings, at the same time, the page is not the whole page refresh, improve the user experience. 3. Creation process: Create an XMLHttpRequest object, that is, create an asynchronous call object; Create a new HTTP request and specify the HTTP request method, URL, and authentication information. Set up functions that respond to changes in the status of HTTP requests. Send an HTTP request; Get the data returned by the asynchronous call; Local refreshes are implemented using JavaScript and DOM.Copy the code

24. What are the advantages and disadvantages of Ajax?

The answer:

1. Flash: Flash is suitable for processing multimedia, vector graphics, access to the machine on CSS, processing text is insufficient, not easy to be searched 2. Ajax: Ajax on CSS, text support is good, support search; 3. Common: With the server no refresh message delivery can detect the user offline and online status operation DOMCopy the code

25, The difference between synchronous and asynchronous?

The answer:

1. The concept of synchronization is probably derived from the concept of synchronization in THE OS: different processes are prioritized (by blocking, waking up, etc.) in order to work together. Synchronization emphasizes orderliness. There is no such ordering in asynchrony. Synchronization: When the browser requests the server, the user sees the page refresh and sends the request again. After the request is complete, the page is refreshed and the user sees the new content and performs the next operation. 2. Asynchronous: The browser requests the server. The user performs normal operations. When the request is finished, the page is not refreshed, the new content will also appear, and the user will see the new content.Copy the code

Explain JavaScript’s same-origin policy.

The answer:

The same protocol, domain name, and port are the same. The same Origin policy is a security protocol. A script that can only read properties of Windows and documents from the same source.Copy the code

27. How to solve cross-domain problems?

The answer:

Jsonp, iframe, window.name, window.postMessage, server set proxy pageCopy the code

Write a generic event listener function.

The answer:


// event(event) toolset
       markyun.Event = {
           // After the page is loaded
           readyEvent : function(fn) {
               if (fn==null) {
                   fn=document;
               }
               var oldonload = window.onload;
               if (typeof window.onload ! ='function') {
                   window.onload = fn;
               } else {
                   window.onload = function() { oldonload(); fn(); }; }},/ / sight, respectively dom0 | | dom2 | | IE way to bind the event
           // Parameters: operation element, event name, event handler
           addEvent : function(element, type, handler) {
               if (element.addEventListener) {
                   // Event type, function to execute, whether to capture
                   element.addEventListener(type, handler, false);
               } else if (element.attachEvent) {
                   element.attachEvent('on' + type, function() {
                       handler.call(element);
                   });
               } else {
                   element['on'+ type] = handler; }},// Remove the event
           removeEvent : function(element, type, handler) {
               if (element.removeEventListener) {
                   element.removeEventListener(type, handler, false);
               } else if (element.datachEvent) {
                   element.detachEvent('on' + type, handler);
               } else {
                   element['on' + type] = null; }},// Prevent events (mainly event bubbling, since IE does not support event capture)
           stopPropagation : function(ev) {
               if (ev.stopPropagation) {
                   ev.stopPropagation();
               } else {
                   ev.cancelBubble = true; }},// Cancel the default behavior of the event
           preventDefault : function(event) {
               if (event.preventDefault) {
                   event.preventDefault();
               } else {
                   event.returnValue = false; }},// Get the event target
           getTarget : function(event) {
               return event.target || event.srcElement;
           },
           // Get a reference to the event object, get all the information about the event, ensure that the event is always available;
           getEvent : function(e) {
               var ev = e || window.event;
               if(! ev) {var c = this.getEvent.caller;
                   while (c) {
                       ev = c.arguments[0];
                       if (ev && Event == ev.constructor) {
                           break; } c = c.caller; }}returnev; }};Copy the code

29, AMD, CMD, Common JS specification differences?

The answer:

AMD implements dependencies early - as early as possible, requireJS is its implementation. CMD implements dependencies on demand - lazy implementation, seaJS is its implementation. CommonJS is the specification for server-side modules, which node.js adopts. The CommonJS specification loads modules synchronously, meaning that subsequent operations cannot be performed until the load is complete. The AMD specification loads modules asynchronously and allows you to specify callback functions.Copy the code

nodejs

1. What are the advantages and disadvantages of Node?

The answer:

Advantages: Because Node is event-driven and non-blocking, it is ideal for handling concurrent requests, so proxy servers built on Node perform much better than servers implemented with other technologies, such as Ruby. In addition, the client code that interacts with the Node proxy server is written in the javascript language, so both the client and server sides are written in the same language, which is a nice thing. Cons: Node is a relatively new open source project, so it's not stable, it's always changing, and it doesn't have enough third-party library support. It looks like Ruby/Rails back in the day.Copy the code

2. How to determine whether the script is currently running in a browser or node environment?

The answer:

Check whether the Global object is window. If not, the script is not running in the browser.Copy the code

Classic Interview questions

1, do not use border draw 1px high line, in different browsers standard mode and weird mode can be consistent effect?

2. What does the following code print on the console? (function () { var a = b = 5; }) (); console.log(b);

Answer: 5

The pitfall of this problem is that there are two names in the immediate function expression, but the variable is declared by the keyword var. That means that a is a local variable of this function. In contrast, B is in global scope.

3. What happens when I execute the following code?

function test () {
	console.log(a);
	console.log(foo());

	var a = 1;
	function foo() {
		return 2;
	}
}
test();
Copy the code

Answer: undefined and 2

Analysis of principle: The reason for this result is that both variables and functions have been promoted (hoisted). Therefore, when a is printed, it already exists in function scope (that is, it is declared), but its value is still undefined.

4. What is the result of the following code?


var fullname = 'John Doe';
var obj = {
	fullname:'Colin Ihrig'.prop: {
		fullname:'Aurelio De Rose'.getFullname: function () {
			return this.fullname; }}};console.log(obj.prop.getFullname());
var test = obj.prop.getFullname;
console.log(test());
Copy the code

Answer: Aurelio De Rosa and John Doe

The reason is that in JavaScript, the context of a function, the object referenced by this keyword, depends on how the function is called, not how the function is defined. In the first console.log() call, getFullname() is called as a function of obj.prop. Therefore, the context here points to the latter and the function returns the fullname attribute of this object. In contrast, when getFullname() is assigned to the value of the test variable, that context points to the global object (window). This is because test is implicitly set as a property of the global object. Therefore, the function call returns the value of the window’s fullname attribute, which in this code is set by the first line of assignment.

5, [“1”, “2”, “3”].map(parseInt)

Answer: [1, NaN, NaN]

Principle analysis: because parseInt requires two parameters (val, radix), radix denotes the radix used for parsing. Map passed 3 elements (Element, index, array), and the corresponding radix was illegal, resulting in the failure of parsing.

Clone (Number, String, Object, Array, Boolean);

The answer:


Object.prototype.clone = function(){
    var o = this.constructor === Array ? [] : {};
    for(var e in this) {
        o[e] = typeof this[e] === "object" ? this[e].clone() : this[e];
    }
    return o;
}
Copy the code

7, How to delete a cookie?

The answer:

1. Set the time to a little ahead of the current time. var date = new Date(); date.setDate(date.getDate() - 1); Document. cookie =' user='+ encodeURIComponent('name') + '; expires = ' + new Date(0)Copy the code

Interview questions

1. How to operate page reconstruction?

The answer:

1. Site refactoring: The act of simplifying structure and adding readability without changing external behavior while maintaining consistency in the front end of the site. The idea is to optimize the site without changing the UI, and maintain a consistent UI while extending it. 2. For traditional websites, reconfiguration is usually: table layout is changed to DIV+CSS; Make the front end compatible with modern browsers (against substandard CSS, such as IE6); Optimization for mobile platforms; Optimize for SEO; 3. Deep site refactoring should consider: reduce code coupling; Make your code flexible; Code strictly according to specifications; Designing extensible apis; Replace the old framework, language (such as VB); Enhance the user experience; 4. Generally speaking, speed optimization is also included in the reconstruction: compression of JS, CSS, image and other front-end resources (usually solved by the server); Application performance optimization (such as data read and write); CDN is used to accelerate resource loading. Optimization of JS DOM; HTTP server file cache;Copy the code

2, List the differences between Internet Explorer and other browsers.

The answer:

Events are different: The element that triggers the event is considered a target. In IE, the target is contained in the srcElement property of the Event object. If the key represents a character (except shift, CTRL, or Alt), IE's keyCode returns Unicode. In the DOM, the keyCode is separated from the character. To obtain the character code, use the charCode attribute. To prevent the default behavior of an event, in IE, returnValue must be set to false. In Mozilla, the preventDefault() method needs to be called. To stop event bubbles, set cancelBubble to true in IE, and call stopPropagation() in Mozzilla.Copy the code

3. Which book is it that 99% of websites need to be refactored?

The answer:

Web Refactoring: Applying Web Standards to Design (Version 2)Copy the code

4. Do you know public key encryption and private key encryption?

The answer:

1. Generally, the private key is used to sign data, and the public key is used to verify the signature. 2. The HTTP website encrypts sensitive data with a public key on the browser and decrypts sensitive data with a private key on the server.Copy the code

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

The answer:

1. Websocket provided by HTML5; 2. Invisible iframe; 3. WebSocket through Flash; 4. XHR connects for a long time; 5. XHR Multipart Streaming; 6. Long linking of <script> tags (cross-domain).Copy the code

6. What are your performance optimization methods?

The answer:

1. Reduce the number of HTTP requests: CSS Sprites, JS, CSS source compression, image size control appropriate; Web Gzip, CDN hosting, data cache, picture server. Front-end template JS+ data, reduce bandwidth waste caused by HTML tags, front-end variables to save AJAX request results, each operation of local variables, no request, reduce the number of requests 3. Use innerHTML instead of DOM operations to reduce DOM operations and optimize javascript performance. 4. Set className instead of style when there are many styles to set. 5. Use fewer global variables and cache DOM node lookup results. Reduce I/O read operations. 6. Avoid CSS Expression, also known as Dynamic properties. 7. Image preloading, style sheets at the top and scripts at the bottom with time stamps. 8. Avoid using tables in the main layout of a page. Tables are not displayed until the content is fully loaded, which is slower than div+ CSS layout. 9. For common websites, there is a unified idea, which is to optimize the front end as far as possible, reduce database operations and reduce disk IO. Optimization refers to the forward end, in the case of does not affect the function and experience, and can not on the server is being executed in the browser, can be directly on the cache server returned to the application server, applications can obtain results don't directly to the external, the machine can achieve the data not to remote, memory to be able to take not to take the disc, Do not query what is in the cache. Reducing database operations means reducing the number of updates, caching results to reduce the number of queries, letting your program complete the database operations as much as possible (such as join queries), reducing disk I/O means minimizing the use of file systems as caching, reducing the number of read and write files, etc. Program optimization is always about optimizing the slow parts, you can't "optimize" in a different language.Copy the code

7. How do you understand the position of front-end interface engineer?

The answer:

1. The front end is the programmer closest to the user, and the ability of the front end is to evolve the product from 90 points to 100 points or better 2. Participated in the project, completed the effect drawing quickly and with high quality, accurate to 1px; 3. Communicate with team members, UI design and product manager; 4. Good page structure, page reconstruction and user experience; 5. Hack, compatible, write beautiful code format; 6. Server optimization and embrace the latest front-end technology.Copy the code

How do you manage your projects?

The answer:

1. The preliminary team must determine the global style (globe.CSS), coding mode (UTF-8), etc.; 2. The writing habits must be consistent (for example, the writing method of inheritance is adopted, and the single style is written in a line); 3. Annotation style writer. All modules are timely annotated (where key styles are called); 4. Annotate the page (such as the start and end of the page module); 5. CSS and HTML are stored in parallel folders and named in the same way (for example, style.css); 6. Store English translations named according to the JS function in separate folders. 7. Integrated images. PNG pNG8 format files should be integrated as much as possible to facilitate future managementCopy the code

Other possible questions, it is always good to prepare

What other technologies do you know besides the front end? What is your greatest skill?

What development tools do you use and why?

What are the ways to optimize and improve CSS performance?

How do browsers parse CSS selectors?

Should I use odd or even fonts on a web page? Why is that?

Which scenes are suitable for margin and padding?

How to write out the style module, say the idea, have any practical experience?

Is the vertical percentage of the element set relative to the height of the container?

How does full-screen scrolling work? Which CSS properties are used?

What is responsive design? What are the fundamentals of responsive design? How to compatibility with earlier Versions of IE?

Parallax scrolling effect, how to animate each page differently? (Go back to the top, slide down to reappear, and only reappear once respectively what to do?)

What’s the difference between a double colon and a single colon in ::before and :after? Explain what these two pseudo-elements do?

How to modify Chrome to remember passwords after automatically filling forms with yellow background?

What do you think of line-height?

What is the display value of an element after it is floated? (automatically becomes display:block)?

To make the font on the page clear and thin how do YOU do that with CSS? (its – the font – smoothing: antialiased;) ?

The font-style property gives it the value “oblique” oblique.

position:fixed; How to deal with invalid under Android?

Overflow: How to handle the problem that scrolling cannot be smooth?

Give a full summary of a project you feel is the best you’ve ever done?

What was the workflow like and how did it work with other people? How to praise the department cooperation?

What do you want to ask or know about the company?

What is the most difficult technical problem you have encountered? How did you solve it?

What libraries are commonly used? Common front-end development tools? What applications or components have you developed?

Overtime?

What do you think of Web apps, hybrid apps and Native apps?

What are the most popular things these days? What websites do you visit?

Briefly describe the development process of mobile APP projects you have done?

What is your role in your current team and what is your obvious impact?

What do you think is a Full Stack developer?

Can you tell me one of your favorite works?

What are your strengths? What are the disadvantages?

How do you manage the front end team?

Do you have your own tech blog and what techniques do you use?

What are you studying recently? Can you tell me where you see yourself in the next three to five years?

What do you think about front-end safety?

Do you know anything about Web injection attacks, how they work, and how well you know about the two most common attacks (XSS and CSRF)?

What are the impressive technical problems encountered in the project? What are the specific problems and how to solve them?

What are you learning these days?

Advanced article

1. What is the difference between thread and process?

The answer:

1. A program has at least one process, and a process has at least one thread. 2. The process has an independent memory unit in the execution process, and multiple threads share the memory, thus greatly improving the efficiency of the program. Each independent thread has an entry point for program execution, a sequential execution sequence, and an exit point for the program. However, threads cannot execute independently and must depend on the application, which provides multiple thread execution control. 5. The meaning of multithreading is that multiple execution parts can be executed simultaneously in an application. However, the operating system does not treat multiple threads as multiple independent applications to achieve process scheduling and management and resource allocation.Copy the code

2. There are a large number of pictures on a page (large e-commerce website), and the loading is very slow. What methods do you have to optimize the loading of these pictures to give users a better experience?

The answer:

1. Lazy image loading, scroll to the corresponding position to load the image. 2. Image preloading. If it is a slide, album, etc., the first and last images displayed will be downloaded first. 3. Use CSSsprite, SVGsprite, Iconfont, Base64, etc., if the image is CSS image. 4. If the image is too large, you can use a specially encoded image, which will load with a particularly compressed thumbnail image first to improve the user experience.Copy the code

3. Where do CSS blocks and JS blocks occur?

The answer:

Blocking features of JS: all browsers block all other activities, such as downloading other resources, rendering content and so on, while downloading JS. Continue to download other resources and render content in parallel until JS has been downloaded, parsed, and executed. In order to improve the user experience, the new generation of browsers support parallel downloading of JS, but JS downloading still blocks downloading of other resources (e.g. Images, CSS files, etc.). Because browsers need to rebuild the DOM tree to prevent JS from modifying it, they block other downloads and renderings. Embedded JS blocks the presentation of all content, while external JS blocks only the display of subsequent content, and both methods block the download of subsequent resources. That is, an external style does not block the loading of an external script, but it blocks its execution.Copy the code

4. How does CSS block loading? CSS can be downloaded in parallel, but when does it block loading (in test observation, CSS in IE6 blocked loading)?

The answer:

When a CSS is followed by an embedded JS, the CSS will block subsequent resource downloads. When you put embedded JS in front of CSS, there is no blocking. Root cause: Because browsers maintain the order of CSS and JS in HTML, stylesheets must be loaded and parsed before the embedded JS executes. The embedded JS will block subsequent resource loading, so the CSS above will block the download.Copy the code

5, Javascript non-blocking loading specific way.

The answer:

1. Place the script at the bottom. <link> is still placed in the head to ensure that the page is loaded properly before the JS loads. The <script> tag comes before </body>. 2. Blocking scripts: Limiting the total number of < scripts > pages can also improve performance because each <script> tag downloads block page parsing. Works with inline and external scripts. 3. Non-blocking scripts: Load the JS code after the page has finished loading. That is, start downloading the code after the window.onload event is emitted. 4. Defer properties: Support for IE4 and FierFox3.5 later browsers 5. Dynamic Script Elements: The Document Object Model (DOM) allows you to dynamically create almost all document content in HTML using JS. <script> var script=document.createElement("script"); script.type="text/javascript"; script.src="file.js"; document.getElementsByTagName("head")[0].appendChild(script); </script>Copy the code

6. How to optimize mobile terminal performance?

The answer:

1. Use CSS3 animation as much as possible and enable hardware acceleration. 2. Use touch events instead of click events as appropriate. 3. Avoid using CSS3 gradient shadows. 4. Hardware acceleration can be turned on with Transform: translateZ(0). 5. Don't abuse Float. Float is computationally expensive in rendering, so use it as little as possible. 6. Web fonts need to be downloaded, parsed, redrawn, and used as little as possible. 7. Use requestAnimationFrame animation instead of setTimeout 8. CSS properties (CSS3 Transitions, CSS3 3D Transforms, Opacity, Canvas, WebGL, Video) will trigger GPU rendering. Please use them appropriately. 9. PC terminal is also applicable to mobile terminalCopy the code

7, talk about the previous end of the perspective of SEO need to consider what?

The answer:

2. Meta Tag optimization 3. 5. Link Exchange and Popularity 6. Use labels properlyCopy the code

8. Common Web security and protection principles?

The answer:

1. SQL injection principle: by inserting SQL commands into Web forms to submit or enter the query string of domain names or page requests, the server can be tricked into executing malicious SQL commands. In general, you should never trust user input, and verify user input by using regular expressions or limiting length, converting single quotes to double "-", and so on. Never use dynamically assembled SQL, instead use parameterized SQL or use stored procedures directly for data query access. Never use database connections with administrator privileges. Use separate, limited database connections for each application. Do not store confidential information in plain text. Encrypt or hash out passwords and sensitive information. 2. Principles and prevention of XSS: XSS (Cross-site scripting) attacks refer to that attackers insert malicious HTML tags or javascript codes into Web pages. For example, an attacker puts a seemingly secure link in the forum, tricking users into clicking on it and stealing the user's private information in the cookie; Or an attacker could add a malicious form to a forum, and when a user submits the form, it sends the information to the attacker's server instead of the trusted site the user thought it was. 3. XSS prevention method: first of all, in the code, the user input places and variables need to carefully check the length and "<", ">", "; , "'" and other characters to filter; Secondly, any content written to the page must be encoded, to avoid accidentally out of the HTML tag. This layer can block at least half of all XSS attacks. Avoid disclosing user privacy, such as email and password, in cookies. Reduce the risk of cookie disclosure by binding cookies to system IP addresses. The cookies obtained by this attacker have no real value and cannot be played back. If the web site does not need to operate on cookies on the browser side, you can add HttpOnly to the end of set-cookie to prevent javascript code from retrieving cookies directly. Use POST instead of GET to submit forms. 4. What's the difference between XSS and CSRF? XSS is about capturing information without having to know the code and packets of other users' pages in advance. CSRF is to complete the specified action on behalf of the user, and need to know the code and packets of other users' pages. To complete A CSRF attack, the victim must complete two steps in sequence: login to trusted website A and generate cookies locally. Visit dangerous site B without logging out of A. 5. CSRF defense: There are many methods of CSRF on the server side, but the general idea is the same, that is, adding pseudo-random numbers on the client page. Through the method of verification codeCopy the code

9. What are HTTP and HTTPS?

The answer:

1. HTTP is usually carried over TCP. A security layer (SSL or TSL) is added between HTTP and TCP, which is called HTTPS. 2. The default HTTP port number is 80 and HTTPS port number is 443. 3. Why HTTPS is secure: Because network requests need to be forwarded by many server routers. Any node in the middle can tamper with the information, whereas if you use HTTPS, the key is between you and the terminal. HTTPS is more secure than HTTP because it uses THE SSL/TLS protocol for transmission. It includes certificate, uninstall, traffic forwarding, load balancing, page adaptation, browser adaptation, refer transfer and so on. This ensures the security of the transmission process.Copy the code