Tell me what you know about closures

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.

Closures have three features:

1. Function nested functions 2. Internal functions can reference external parameters and variables 3. Parameters and variables are not collected by the garbage collection mechanism

Please talk about the disadvantages of cookies

Although cookies provide convenience in persisting client data and share the burden of server storage, they still have many limitations. First: generate a maximum of 20 cookies per specific domain name

2.IE7 and later versions can end up with 50 cookies. Firefox has a maximum of 50 cookies. Chrome and Safari have no hard limitCopy the code

IE and Opera will clean the least recently used cookies, Firefox will randomly clean cookies.

The maximum size of a cookie is 4096 bytes. Generally, the maximum size is 4095 bytes for compatibility.

Internet explorer provides a way to store persistent userdata called userdata, which has been supported since Internet explorer 5.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.

Advantages: High scalability and availability

1. Control the size of session objects stored in cookies through good programming. 2. Use encryption and secure transmission technology (SSL) to reduce the possibility of cookie cracking. 3. Store insensitive data only in cookies, so there will be no significant loss even if it is stolen. 4. Control the lifetime of cookies so that they do not last forever. The thief probably got hold of an expired cookie.Copy the code

Disadvantages:

1. Limit the number and length of 'cookies'. Each domain can have a maximum of 20 cookies. The length of each cookie cannot exceed 4KB; otherwise, the cookie will be truncated. 2. 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. 3. 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.Copy the code

Browser local storage

In older browsers, JS provides sessionStorage and globalStorage. LocalStorage is provided in HTML5 to replace globalStorage.

Html5 Web Storage includes two Storage methods: sessionStorage and localStorage.

SessionStorage is used to store data in a session locally, which can only be accessed by pages in the same session and is destroyed when the session ends. Therefore, sessionStorage is not a persistent local storage, only session level storage.

And localStorage for persistent localStorage, unless actively delete data, otherwise the data is never expired.

Difference between Web storage and cookies

The concept of Web Storage is similar to cookie, except that it is designed for larger Storage capacity. Cookie size is limited, and every time you request a new page when the Cookie will be sent in the past, so virtually waste bandwidth, in addition to Cookie also need to specify scope, can not be called across the domain.

In addition, Web Storage with setItem, the getItem, removeItem, methods of the clear, don’t like cookies need encapsulation setCookie front-end developer himself, getCookie.

But cookie is also not possible or missing: 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 “store” data in the local

Browser support 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.

Both localStorage and sessionStorage have the same operation methods, such as setItem, getItem, and removeItem

The difference between cookies and sessions:

1. Cookie data is stored in the client's browser, and session data is stored on the server. 2. Cookies are not very secure. Others can analyze cookies stored locally and cheat cookies. 3. Sessions are stored on the server for a certain period of time. Cookies should be used to reduce server performance when the number of accesses increases. 4. The data saved by a single cookie cannot exceed 4K. Many browsers limit the maximum number of cookies saved by a site to 20. 5. Therefore, personal advice: Store important information such as login information as SESSION and other information in cookies if necessaryCopy the code

CSS Related Issues

Display: None and visibility:hidden difference?

Display: None Hides the corresponding element, no more space is allocated to it in the layout of the document, and its edges are closed as if it never existed. Visibility: Hidden the corresponding elements, but retain the original space in the document layout.Copy the code

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

(1) Link is an HTML tag, while @import is provided by 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 can only be recognized above IE5, while link is AN HTML tag without compatibility problems; (4) The link style has a higher weight than the @import style.Copy the code

Position: Similarities and differences between absolute and float properties

A: Common: Setting 'float' and 'absolute' properties on inline elements takes the element out of the document flow, and can set its width and height. B: Difference: Float still occupies position, position overrides other elements in the document flow.Copy the code

What about the box-sizing property?

The box-sizing attribute is mainly used to control the parsing mode of the box model of elements. The default value is content-box.

  • Content-box: Lets elements maintain the W3C’s standard box model. The width/height of the element is determined by the width/height of the border + padding + Content. Setting the width/height attribute refers to the width/height of the content portion

  • Border-box: Allows elements to maintain the traditional IE box model (IE6 below and ie6-7 weird mode). Setting the width/height attribute refers to the border + padding + content

Under the standard browser, according to the W3C specification of the box model analysis, once the border or inner distance of the element is modified, it will affect the box size of the element, it has to recalculate the box size of the element, thus affecting the layout of the whole page.

What are the CSS selectors? Which attributes can be inherited? How is the priority algorithm calculated? CSS3 new pseudo class has those?

Id selector (# myID) 2. Class selector (.myclassName) 3. Tag selector (div, H1, P) 4. Adjacent selector (H1 + P) 5. Child selector (UL > LI) 6. Descendant selector (Li A) 7. Wildcard selector (*) 8. Attribute selector (a[rel = "external"]) 9. Pseudoclass selector (A: hover, Li :nth-child)Copy the code
  • Font-size font-size -family color, text-indent;

  • Non-inheritable style: border padding margin width height;

  • The nearest priority principle shall prevail if the style definition is the nearest in the case of the same weight;

  • The loading style is based on the last loaded location;

The priorities are:

! Important > id > class > tag important has a higher priority than inline, but inline has a higher priority than IDCopy the code

CSS3 added pseudo class example:

P :first-of-type Selects the first element belonging to its parent element

Each of the elements

Elements. P :last-of-type selects the last element belonging to its parent element

Each of the elements

Elements. P :only-of-type Selects the value that is unique to its parent element

Each of the elements

Elements. P :only-child Selects each of the unique child elements that belong to its parent element

Elements. P :nth-child(2) selects each of the second child elements belonging to its parent

Elements. :enabled :disabled Controls the disabling status of form controls. : Checked check boxes or check boxes are selected.

Copy the code

To whom are the values of position, relative and Absolute located?

Absolute Generates an element that is absolutely positioned, relative to the parent element that is not static. Fixed (not supported by old IE) generates an absolutely positioned element, positioned relative to the browser window. Relative generates elements that are positioned relative to their position in a normal flow. Static Default value. Without positioning, the element appears in normal flowCopy the code

What’s new with CSS3?

CSS3 implements border-radius, box-shadow, text-shadow, linear gradient, Transform :rotate(9DEg) scale(0.85,0.90) Translate (0px,-30px) skew(-9deg,0deg); rotate(9deg) scale(0.85,0.90) Translate (0px,-30px) skew(-9deg,0deg); // Rotate, zoom, position, tilt adds more CSS selectors multi-background RGBA in CSS3 the only pseudo-element introduced is :: Selection. Media query, multi-column layout border-imageCopy the code

The difference between XML and JSON?

(1) Data volume. JSON is smaller and faster than XML. (2) Data interaction. JSON and JavaScript interaction is more convenient, easier to parse processing, better data interaction. (3) Data description. JSON is less descriptive of data than XML. (4) Transmission speed. JSON is much faster than XML.Copy the code

Understanding of the BFC specification?

BFC, block-level formatting context, a box that creates a new BFC is laid out independently, and the style of the child elements inside the box does not affect the outside elements. Two adjacent block-level boxes in the same BFC will collapse at the vertical (relative to the layout direction) margin. (A concept in the W3C CSS 2.1 specification that determines how an element lays out its content and how it relates and interacts with other elements.)Copy the code

Explain CSS sprites and how you can use them in your pages or websites.

CSS Sprites is actually to integrate some background images in the web page into a picture file, and then use the combination of "background-image", "background-repeat", and "background-position" of CSS for background positioning. Background-position can be used to accurately locate the position of the background image. This can reduce the overhead of many image requests, because the request takes a long time; Requests can be concurrent, but they are limited to six in most browsers. For the future, there is no need to do this because of http2.Copy the code

HTML part

What is your understanding of semantics?

1. It can make the page present a clear structure when removing or losing the style. 2. 3, it is convenient for other devices to parse (such as screen readers, blind readers, mobile devices) to render web pages in a meaningful way; 4, easy to team development and maintenance, semantic more readable, is the next step of the important trend of the web page, follow the W3C standard team follow this standard, can reduce differentiation.Copy the code

Doctype? How to distinguish strict mode from promiscuous mode? What do they mean?

(1) The declaration is first in the document, before the tag. Tells the browser which mode to render the document in. (2) strict mode of typesetting and JS mode of operation is to support the browser to run the highest standard. (3) In promiscuous mode, pages are displayed in a loosely backward compatible manner. Emulate the behavior of older browsers in case the site doesn't work. (4) DOCTYPE does not exist or is incorrectly formatted, resulting in the document being presented in promiscuous mode.Copy the code

How many Doctype document types do you know?

This tag 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. Standards (aka strict rendering) mode is used to render web pages that conform to the latest Standards, while Quirks (aka loose rendering or compatibility) mode is used to render web pages designed for traditional browsers.Copy the code

HTML vs. XHTML – What’s the difference

Differences: 1. All tags must have a corresponding closing tag. 2. All tag element and attribute names must be lowercase 3. All XML tags must be properly nested. 4. All attributes must be enclosed in quotation marks. Encode all < and & special symbols to represent 6. Assign a value ="" 7 to all attributes. Do not use "--" ="" 8. Images must have caption ="" <="" "code=""/>Copy the code

Common Compatibility Problems?

* PNG24 bit images appear in the background in iE6, the solution is to make PNG8. * The browser default margin and padding are different. Margin :0; margin:0; padding:0; } to unify. * IE6 double Margin bug: After the block property tag float, margin is displayed in IE6 larger than the set margin. * Double distance caused by floating IE (IE6 double distance problem: Under IE6, if you float an element and set margin-left or margin-right at the same time, the margin value is doubled.) #box{ float:left; width:10px; margin:0 0 0 100px; } In this case, IE will produce a distance of 20px. The solution is to add -- _display:inline; Convert it to an inline property. (_ this symbol is recognized only by IE6) * Progressive recognition, which gradually removes parts from the whole. First of all, the clever use of the "\9" mark, the IE viewer from all the situation out. Then, use "+" again to separate IE8 and IE7 and IE6, so that IE8 has been independently identified. css .bb{ background-color:#f1ee18; Background-color :#00deff\9; background-color:#00deff\9; /*IE6, 7, 8 */ +background-color:#a200ff; /*IE6, 7 */ background-color:#1e0bd1; /*IE6 recognize */} * In IE, you can use the method of getting regular attributes to obtain custom attributes, or you can use getAttribute() to obtain custom attributes; In Firefox, you can only use getAttribute() to obtain custom attributes. * In IE, the event object has x and Y attributes, but no pageX and pageY attributes. In Firefox, the Event object has the pageX and pageY properties, but not the X and Y properties. * Chrome's Chinese UI forces text smaller than 12px to be displayed at 12px by default, by adding the CSS attribute -webkit-text-size-adjust: None; Hover styles no longer hover or active after A hyperlink has been clicked. A: Link {} a:visited {} A :hover {} a:active {} * Weird mode problem: Missing a DTD declaration, Firefox will still parse web pages in standard mode, but in IE will trigger weird mode. To avoid unnecessary trouble with weird schemas, it's best to get into the habit of writing DTD declarations. You can now use the [HTML] (http://www.w3.org/TR/html5/single-page.html) recommended method: * Margin-left and margin-right of two adjacent divs will not overlap, but margin-top and margin-bottom will overlap. Solution, develop good code writing habits, use both margin-top and margin-bottom. * Internet Explorer 6 does not support PNG image format wellCopy the code

Explain float and how it works? Tips for cleaning up floats

Floating elements leave the document flow and do not take up space. The floating element touches the border that contains it or stays in the border of the floating element. 1. Use empty labels to clear floats. This method is to add an empty tag definition CSS clear:both. The downside is adding meaningless labels. 2. Use Overflow. Add CSS property overflow:auto to parent tag that contains floating elements; zoom:1; Zoom :1 is compatible with Internet Explorer 6. 3. Use after pseudo-objects to clear floats. This method only applies to non-Internet Explorer browsers. The specific writing method can refer to the following examples. Note the following points in use. Height :0 must be set in the pseudo-object where the floating element is to be cleared, otherwise the element will be several pixels higher than it really is.Copy the code

What are the problems and solutions caused by floating elements?

Problems caused by floating elements: (1) the height of the parent element cannot be open, influence elements of the parent element size and (2) with the floating element at the same level of the floating element (inline element) will follow that float (3) were it not for the first element is the element before the elements also need to float, otherwise it will affect the structure of the pageCopy the code

Solution: Use the CSS clear:both; Property to clear the float of the element solves problems 2 and 3. For problem 1, add the following style to the parent element:

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

There are several ways to clear floats:

1. Extra label methodCopy the code
     
(Cons: Adding extra tags makes the HTML structure look less concise.) #parent:after{content:"."; height:0; visibility:hidden; display:block; clear:both; } 3, float external element 4, set 'overflow' to 'hidden' or 'auto'

What is the difference in the box model in IE 8 below

The width and height of elements defined in the box model of IE8 below do not include inside margins and bordersCopy the code

DOM manipulation – how to add, remove, move, copy, create, and find nodes.

Create a new node createDocumentFragment() // Create a DOM fragment createElement() // create a specific element createTextNode() // Create a text node (2) Add, remove, replace, insert AppendChild () removeChild() replaceChild() insertBefore() // Insert a new child before the existing one (3) find getElementsByTagName() // through the tag name GetElementsByName () // getElementById() // Unique by element IDCopy the code

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?

* HTML5 is no longer a subset of SGML, it's all about adding graphics, location, storage, multitasking, etc. * Drag release (Drag and drop) API semantic better content labels (header, nav, footer, value, the article, section), audio and video API (audio, video) Canvas (Canvas) API Geolocation API Local offline storage localStorage Stores data for a long time. Data is not lost after the browser is closed. SessionStorage data automatically deletes form controls when the browser is closed, Calendar, Date, Time, email, URL, search New technologies Webworker, websocket, Geolocation * Removed elements pure presentation elements: Basefont, Big, Center, FONT, S, Strike, TT, U; Elements that negatively affect usability: Frame, Frameset, Noframes; * 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. Html5shim framework how to distinguish: DOCTYPE declaration/new structural elements/functional elementsCopy the code

Pros and cons of iframe?

2. Disadvantages of '<iframe>' : * Iframe blocks Onload event on main page; * Instant content is empty and takes time to load * no semanticsCopy the code

How to implement communication between multiple tabs in the browser?

Invoke local storage methods such as localStorge and cookiesCopy the code

The difference between thread and process

A program has at least one process, and a process has at least one thread. The scale of thread partition is smaller than that of process, which makes the concurrency of multithreaded program high. In addition, the process has an independent memory unit during execution, while multiple threads share the memory, thus greatly improving the efficiency of the program. Threads are different from processes in their execution. 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. From a logical point of view, the meaning of multithreading is that multiple parts of an application can be executed simultaneously. However, the operating system does not treat multiple threads as multiple independent applications to achieve process scheduling and management and resource allocation. This is an important difference between a process and a thread.Copy the code

How do you optimize your site’s files and resources?

Expected solutions include: file merge file minimization/file compression using CDN managed cache use (multiple domain names to provide cache) othersCopy the code

Name three ways to reduce page load time.

1. Optimize the picture 2. Image format selection (GIF: provide less color, available in some of the color requirements are not high) 3. Optimize CSS (compress and merge CSS, e.g. Margin-top,margin-left...) 4. The url is followed by a slash (such as www.campr.com/ directory, will determine the "directory is a file type, or directory.) 5. Specify height and width. (If the browser doesn't find these two parameters, it needs to calculate the size as it downloads the image, and if there are many images, the browser needs to constantly adjust the page. This affects not only speed but also the browsing experience. When the browser knows the height and width parameters, even if the image is temporarily unavailable, the page will make space for the image and continue to load content. Loading times are faster and browsing is better.) 6. Reduce HTTP requests (merge files, merge images).Copy the code

What tools do you use to test code performance?

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

What is FOUC (style-free content flicker)? How do you avoid FOUC?

FOUC - Flash Of Unstyled Content Document style flashing @import ".. /fouc.css"; The @import that references CSS files is the culprit. IE will first load the ENTIRE HTML document DOM, and then to import external CSS files, therefore, in the page DOM loading completed to CSS import completed in the middle will have a period of time on the page content is no style, the length of this period of time with network speed, computer speed are related. The solution is surprisingly simple, just add an or in betweenCopy the code

The difference between null and undefined?

Null is an object representing “none” and is zero when converted to a value; Undefined is a primitive value for “none”, which is NaN when converted to a value.

When the declared variable has not been 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.

Undefined means “missing value”, that is, there should be a value here, but it is not defined yet. Typical usage:

(1) If a variable is declared but not assigned, it is undefined. (2) When the function is called, the argument that should be provided is not provided, which is equal to undefined. (3) The object has no assigned attribute. The value of this attribute is undefined. (4) If the function does not return a value, undefined is returned by default.Copy the code

Null means “no object”, meaning there should be no value. Typical usage:

(1) as the parameter of the function, indicating that the parameter of the function is not an object. (2) as the end of the object prototype chain.Copy the code

What exactly does the new operator do?

1. Create an empty object that is referenced by this and inherits the prototype of the function. Properties and methods are added to the object referenced by this. 3. The newly created object is referenced by this and returns this implicitly. var obj = {}; obj.__proto__ = Base.prototype; Base.call(obj);Copy the code

What are the ways to lazily load JS?

Defer and Async, create DOM dynamically (create script, insert into DOM, callBack after loading), and load JS asynchronously on demandCopy the code

How to solve cross-domain problems?

Jsonp, document.domain+iframe, window.name, window.postMessage, server set proxy page JSONP principle is to dynamically insert script tagsCopy the code

For details, see: Js cross-domain problem

The difference between documen.write and innerHTML

Document.write can only redraw the entire pageCopy the code

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

Function: Dynamically changes the operating environment of a method on a class. Function () function () function (

What operations 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 refer to 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. Using a string instead of a function as the first argument to setTimeout causes a memory leak. Closures, console logging, loops (a loop is created when two objects reference and retain each other)Copy the code

See js variables, scope, and memory for details

Scope and variable declaration enhancement in JavaScript?

See: JavaScript function patterns for details

How do I determine whether the script is currently running in a browser or node environment?

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

Other questions?

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

List the features that make Internet Explorer different from other browsers.

What is graceful degradation and progressive enhancement?

Graceful degradation: The Web site works in all modern browsers, and if the user is using an older browser, the code checks to make sure they work. Due to the unique box layout of Internet Explorer, hacks for different versions of Internet Explorer have been elegantly degraded, adding candidates for browsers that can't support functionality that degrades the experience in some way on older browsers without completely failing. Progressive enhancement: Starting with basic features supported by all browsers, gradually add features that are only supported by modern browsers, adding additional styles and features to pages that are not harmful to the base browser. They are automatically rendered and functional when supported by the browser.Copy the code

See: CSS learning summary (1)

How do WEB applications actively push Data from the server to the client?

Javascript Data push

Commet: Server push technology based on HTTP long connections

Push scheme based on WebSocket

Server-send Event (SSE) : a new method for the Server to 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, closer than the back end, database, product manager, operations, and security. With Node.js, the front end can realize some things on the service side. The front end is the programmer closest to the user. The ability of the front end is to enable the product to evolve from 90 points to 100 points, or even better. Communicate with team members, UI design, product manager; Good page structure, page reconstruction and user experience; Hack, compatible, write beautiful code format; Server optimization, embrace the latest front-end technology.Copy the code

What performance optimization methods do you have?

(See Yahoo’s 14 Performance Optimization Principles for more details).

(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. (2) Front-end template JS+ data to reduce bandwidth waste caused by HTML tags. Front-end variables are used to save AJAX request results, so local variables are not required for each operation to reduce the number of requests. (3) Use innerHTML instead of DOM operations to reduce the number of DOM operations and optimize javascript performance. (4) Set className instead of style when there are many styles to set. (5) Use less global variables and cache the results of DOM node search. Reduce I/O read operations. Avoid using CSS Expression, also known as Dynamic properties. (7) Image preloading, style sheets at the top, scripts at the bottom with time stamps.Copy the code

Details: segmentfault.com/blog/trigki…

What happens when a page is loaded and displayed from the time the URL is entered?

There are four steps: (1) when a URL request is sent, no matter whether the URL is the URL of the Web page or the URL of each resource on the Web page, the browser will start a thread to process the request and start a DNS query on the remote DNS server. This enables the browser to obtain the IP address corresponding to the request. (2), the browser establishes a TCP/IP connection with the remote Web server through TCP three-way handshake negotiation. The handshake consists of a synchronization message, a synchro-reply message, and a reply message, which are transmitted between the browser and the server. In this handshake, the client first attempts to establish a communication, then the server responds and accepts the client's request, and finally the client sends a message that the request has been accepted. (3), once a TCP/IP connection is established, the browser sends an HTTP GET request to the remote server over the connection. The remote server finds the resource and returns it with an HTTP response, and an HTTP response status of 200 indicates a correct response. (4) at this point, the Web server provides resource services and the client starts to download resources. Once the request is returned, it goes to the front end module that we're looking at. In short, the browser will parse the HTML to generate a DOM Tree, and then it will generate a CSS Rule Tree from CSS, and javascript can manipulate the DOM from the DOM APICopy the code

Details: What happens between entering the URL and the browser receiving it?

How do you manage your projects?

The initial team must determine the global style (globe.CSS), encoding pattern (UTF-8), etc. The writing habits must be consistent (for example, each style is written in a single line using inheritance); Annotation style writer, all modules are timely annotation (annotation key style call place); Annotate pages (e.g. start and end of page modules); CSS and HTML should be stored in parallel folders and named in the same way (for example, style.css). JS folders store English translations named according to the JS function. Png8 format files are used as far as possible to integrate together to facilitate future managementCopy the code

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

Node.js, Mongodb, NPM, MVVM, MEAN, three.js,React. Website: w3cfuns, sf, hacknews, CSDN, mu class, blog garden, InfoQ, w3cplus, etcCopy the code

Several ways to create javascript objects

Factory pattern 2, constructor pattern 3, prototype pattern 4, hybrid constructor and prototype pattern 5, dynamic prototype pattern 6, Parasitic constructor pattern 7, secure constructor patternCopy the code

Six ways to Inherit javascript

1, prototype-chain inheritance 2, borrowed constructor inheritance 3, combinatorial inheritance (prototype + borrowed construction) 4, prototype-inheritance 5, parasitic inheritance 6, parasitic combinatorial inheritanceCopy the code

Details: JavaScript inheritance details

Ajax process

(1) Create an XMLHttpRequest object, that is, create an asynchronous call object. (2) create a new HTTP request and specify the method, URL, and validation information for the HTTP request. (3) set up a function that responds to changes in the status of the HTTP request. (4) Send the HTTP request. (5) get the data returned by the asynchronous call. (6) Use JavaScript and DOM to achieve local refresh.Copy the code

Ajax and Http status words

Asynchronous loading and lazy loading

1. Asynchronous loading: dynamically insert script tags. 2. Get JS code through Ajax and execute it through Eval. Create and insert iframe to execute JS asynchronously. 5. Lazy loading: Some JS code is not required immediately when the page is initialized, but later in some cases.Copy the code

Front-end security issues?

Principles of SQL Injection

By inserting SQL commands into Web forms to submit or enter query strings for domain names or page requests, the server can be tricked into executing malicious SQL commands.

In general, there are the following points:

1. Do not trust user input. To verify user input, use regular expressions or limit the length to convert single quotation marks to double "-". 2. Never use dynamic assembled SQL, use parameterized SQL or directly use stored procedures for data query access. 3. Never use database connections with administrator privileges. Use separate database connections with limited privileges for each application. 4. Do not store confidential information in plain text. Encrypt or hash passwords and sensitive information.Copy the code

XSS principle and prevention

Xss(Cross-site Scripting) attacks refer to the insertion of malicious HTML tags or javascript code 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.

XSS defense methods

1. In the code, the user input places and variables need to be carefully checked for length and for “<“, “>”, “; , “‘” 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. 2. Avoid disclosing user privacy, such as email and password, in cookies. 3. Bind the cookie to the system IP address to reduce the risk of cookie leakage. The cookies obtained by this attacker have no real value and cannot be played back. 4. Use POST instead of GET to submit forms

What is 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:

1. Log in to trusted website A and generate cookies locally. 2. Visit dangerous website B without logging out of A.

CSRF defense

1. There are various CSRF methods on the server side, but the general idea is the same, that is, adding pseudo-random numbers to the client page. 2. Use the verification code

How many resources can be downloaded in parallel with each version of Internet Explorer and Chrome

Two concurrent IE6, six concurrent iE7 updates, six Firefox and six Chrome versionsCopy the code

How do you implement inheritance in javascript, and how do you avoid object sharing on the prototype chain

The classic extend() function, which many front-end frameworks encapsulate, uses an empty function as an intermediate variableCopy the code

Usage of Grunt, YUI Compressor, and Google Clojure for code compression.

YUI Compressor is a tool for compressing JS and CSS files. It is developed in Java. Usage: // Compressed JS java-jar yuicomPresSOR-2.4.2. jar --type JS --charset UTF-8 -v src.js > Packed Yuicompressor-2.4.2. jar --type CSS -- Charset UTF-8 -v src. CSS > Packed. CSSCopy the code

See: Front-end Code Performance Optimization Tools you need

What are the advantages and disadvantages of Flash and Ajax?

1, Flash Ajax contrast Flash is suitable for processing multimedia, vector graphics, access to the machine; On CSS, processing text is insufficient and not easy to search. Ajax is great for CSS, text support, and search support; Insufficient multimedia, vector graphics, machine access. Common features: no refresh messaging with the server, user offline and online status, DOM manipulationCopy the code

Explain JavaScript’s same-origin policy.

Concept: Same-origin policy is an important security metric for client-side scripts, especially Javascript. It originated in Netscape Navigator2.0 to prevent a document or script from being loaded from multiple sources.

The same origin policy indicates that the 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.

Why the homology restriction?

Let’s take an example: a hacker program, for example, he uses Iframe to embed the real bank login page into his page, when you use the real username and password login, his page can read the content in your form input through Javascript, so that the username and password can be easily obtained.

What is “use strict”; ? What are the advantages and disadvantages of using it?

ECMAscript 5 adds a second mode: “Strict mode”. As the name suggests, this mode makes Javascript run under more stringent conditions.

The main objectives of the Strict Mode are as follows:

- Eliminate some unreasonable and inaccurate Javascript syntax, reduce some weird behavior; -Eliminate some unsafe parts of the code operation to ensure the safety of the code operation; - Improve compiler efficiency, increase running speed; - Setting the stage for future versions of Javascript.Copy the code

Note: After testing IE6,7,8, and 9 do not support strict mode.

Cons: JS is now compressed, some files are in strict mode, others are not. Merge files in strict mode, and the string is inserted into the middle of the file, not indicating strict mode, but wasting bytes after compression.

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

GET: used to obtain information. The URL is used to transfer parameters. The number of messages to be sent is limited to 2000 characters. GET uses Request.QueryString to GET the value of a variable, while POST uses Request.Form to GET the value of a variable. GET uses the address bar to GET the value, and POST uses the Form to submit the value. However, use POST requests in cases where you cannot send large amounts of data to the server using a cache file (updating a file or database on the server) (POST has no data limit) and POST is more stable and reliable than GET when sending user input that contains unknown charactersCopy the code

Where does CSS block and where does JS block?

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.

How can CSS block loading? CSS can be downloaded in parallel, under what circumstances can block loading occur (in test observation, CSS in IE6 is blocked loading)

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.

Where should embedded JS be placed?

1. Placing it at the bottom will still block all rendering, but not resource downloads. If the embedded JS is in the head, put the embedded JS in the CSS header. 4. Do not call long-running functions from embedded JS. If you must, use 'setTimeout' insteadCopy the code

How to load Javascript without blocking