- Interview summary a: 2018 dachang advanced front end questions summary
- Advanced interview: [semi-monthly] summary of high-frequency interview questions and answers
CSS content
Responsive layout
A comparison of the three prevailing precompilers
- CSS preprocessors use a specialized programming language to style Web pages and then compile them into normal CSS files for use by projects.
- Make your CSS simpler, more adaptable, more readable, and easier to maintain.
The difference between less, Sass and stylus
-
1. The variables:
- Sass declares that variables must begin with “$” followed by the name and value of the variable, and that the name and value are separated by a colon:.
- Less declares variables with “@” at the beginning, the rest of the same as Sass.
- Variables declared in Stylus are not qualified; the ending semicolon is optional, but there must be an “equal sign” between the variable name and its value.
-
2. Scope:
- Sass: The worst of the three, there is no concept of global variables. That means you have to be careful when you define variables with the same name in Sass.
- Less: The last updated variable is valid and applies to all references!
- Stylus: The processing method of Sass is the same as that of Stylus. The output value of a variable is calculated according to the last previous definition, and each reference to the latest definition is valid.
-
3. The nested:
- The “selector nesting” of the three CSS precompilers is identical in use, even to the tags that refer to the parent selector.
-
4. Inheritance:
- Sass inherits styles from one selector to another, much like Stylus. Start with “@extend”, followed by the inherited selector. Stylus inherits from Sass in the same way.
- Less uses pseudo class to describe inheritance relationship.
-
5. Import @import:
- Variable interpolation can only be done in Sass if the URL () expression is introduced:
$device: mobile; @import url(styles.#{$device}.css); Copy the code
- Less allows interpolation in strings:
@device: mobile; @import "styles.@{device}.css"; Copy the code
- Interpolation doesn’t work here in Stylus, but you can take advantage of its string concatenation capabilities:
device = "mobile" @import "styles." + device + ".css" Copy the code
-
conclusion
- 1. Grammatical rigor in Sass and Less while Stylus is relatively free. Because Less looks more like CSS, it might be easier to learn.
- 2.Sass and Compass, Stylus and Nib are good gay friends.
- 3.Sass and Stylus both have language-like logical processing: conditions, loops, etc. Less is not as good as Sass or Stylus in simulating these functions with keywords like When.
- 4.Less is inferior to the Sass and Stylus in richness and character, and would not be as widely used as it is today if Bootstrap had not introduced it (personal opinion).
Link and @import are distinguished and selected
<style type="text/css"> @import url(CSS file path address); </style> <link href="CSSurl path" rel="stylesheet" type="text/css" /
Copy the code
- Link has many functions, such as RSS, Rel, etc., while @import can only be used to load CSS.
- When a link is parsed, the page loads the referenced CSS synchronously, while the CSS referenced by @import waits until the page is loaded.
- @import requires Internet Explorer 5 or higher.
- Link can be dynamically imported using JS, @import cannot;
Vertically centered layout
CSS Classic Layout series 1 – vertically centered layout
Examples of advanced features of CSS3
What content or apis have been added and used in H5?
1 pixel border problem
What is landing
What is landing
- Block formatting context. Block-level formatting context;
- Formatting context is a rendering area of a page that has its own set of rendering rules, determining how its children are positioned and how they relate to and function with their siblings.
- BEC has the following features
- The inner boxes will be placed vertically, one after the other, starting from the top;
- The vertical distance of the box is determined by margin. The margins of two adjacent boxes belonging to the same BFC will be folded;
- The left margin of each element’s margin box touches the left side of the border box containing the block. This is true even for floating elements;
- BFC areas do not overlay with float boxes;
- When calculating the height of the BFC, the floating child element also participates in the calculation.
- The text layer is not covered by the floating layer and surrounds the surroundings
The CSS property that generates the BFC function
- Float A value other than None;
- Overflow values other than visible (hidden, auto, scroll);
- Display (table-cell, table-caption, inline-block, flex, inline-flex);
- Position (absolute, fixed) will automatically create BFC;
Landing the role of
- One of the biggest uses of the BFC is to have a separate container on the page so that the layout of elements inside and outside the container does not affect each other.
- Solve the upper margin overlap; BFC is enabled for both overlapping boxes;
- Solve floating caused by height collapse; Container box open BFC;
- Solve text surround picture; Left image div, right text container P, open BFC for p;
Js based
for… In and for… Of the difference between
- for… in
- 1. The looped index is a string number.
- 2. Traversal order may not follow the internal order of the actual array;
- 3. Using for in iterates through all enumerable properties of an array, including stereotypes and array custom properties.
- So for in is better for traversing objects, not for in groups.
- It is recommended to use for… when looping object properties. In, use for when iterating through groups… Of;
- for… In loops for key, for… Of loops out value;
- Note that for… Of is a new feature introduced in ES6. Fixed for… introduced in ES5 The deficiency of in;
- for… Of cannot loop through ordinary objects, and must be used with object.keys ();
Object.prototype.objCustom = function () {};
Array.prototype.arrCustom = function () {};
let iterable = [3, 5, 7];
iterable.foo = "hello";
for (let i in iterable) {
console.log(i); // logs 0, 1, 2, "foo"."arrCustom"."objCustom"
}
for (let i of iterable) {
console.log(i); // logs 3, 5, 7
}
Copy the code
Script introduction:
- HTML static ‘, then just insert a string in the DOM, let alone the js string, so you can’t use this method to insert script!!
- For example: 1.js depends on 2.js, 2.js depends on 3.js; The actual loading order is 1.js, 2.js, 3.js
- Note: the actual order in which modules run is 3.js, 2.js, 1.js. So, file loading, file running after loading, module running, these are three things, don’t mix it up.
// 1.js require([],functionA() {// main logic code})Copy the code
- File loading: will
<script src='1.js'>
After the node is inserted into the DOM, the 1.js file is downloaded. - After loading the file, execute the code in 1.js, that is, execute the require() function!!
- Module: require callback function, above, the main logic code, the functionA function run!!
- File loading/file running order: 1.js, 2.js, 3.js;
- Module running sequence: 3.js, 2.js, 1.js;
Webpack contrast requirejs
- Webpack does not need to encapsulate a layer of things like requireJS when managing modules
define(['jquery'].function(jquery){})
Copy the code
- It implements front-end code modularization, improves code reuse, and provides cache function for common modules.
- Webpack packs its own module’s javascript and common javascript separately for different pages, while requireJS packs all javascript files into a single file, making common JS modules across multiple pages on a site impossible to cache.
- Webpack introduces split points and chunks, which define all the dependent modules and add up to a code block to make a page reference to a code block.
The mainstream framework Vue
How is the DIff algorithm implemented in VUe2?
- Reference: Make the virtual DOM and DOM-diff out of your way
- When data changes, the set method will call dep. notify to notify all subscribers Watcher, and the subscribers will call Patch to patch the real DOM and update the corresponding view.
The diff process
- The patch function receives two arguments oldVnode and Vnode representing the new node and the previous old node respectively
- Determine whether the two nodes are worthy of comparison, and then execute patchVnode.
- If not, replace oldVnode with Vnode;
- PatchVnode: When we determine that the two nodes are worth comparing, we will specify the patchVnode method for the two nodes.
- Find the corresponding real DOM, called EL;
- Check whether Vnode and oldVnode refer to the same object. If so, return.
- If they both have text nodes and are not equal, set the text node of EL to the text node of Vnode;
- If oldVnode has children and Vnode does not, remove el’s children.
- If oldVnode does not have children and Vnode does, materialize the children of Vnode and add them to EL.
- If both have child nodes, it is important to perform the updateChildren function to compare child nodes.
- UpdateChildren function diagram
- There are four ways to compare samevNodes in oldS, oldE, S, and E. When two of them match, the corresponding node in the real DOM will be moved to the corresponding position in Vnode.
- If oldS and E match, the first node in the real DOM moves to the end;
- If oldE and S match, the last node in the real DOM moves to the front, and the two matched Pointers move toward the center.
- If none of the four matching pairs are successful, then oldChild and S will be traversed and matched one by one, and the successful node will be moved to the front in the real DOM after successful matching. If there are still no successful nodes, the node corresponding to S will be inserted into the corresponding oldS position in dom, and the pointer of oldS and S will be moved to the middle.
Vue bidirectional data binding
- Vue. js adopts data hijacking combined with publiser-subscriber mode. It hijacks the setter and getter of each attribute through Object.defineProperty() to publish messages to subscribers when data changes and trigger corresponding listening callback.
- Step 1: Perform recursive traversal of Observe’s data objects, including setters and getters for properties of child properties. So, if you assign a value to this object, it will trigger the setter, so you can listen for changes in the data;
- Second step: Compile parse template instructions, replace variables in the template with data, and then initialize render page view, bind the corresponding node of each instruction to update function, add subscribers to listen to the data, once the data changes, receive notification, update view;
- Step 3: The Watcher subscriber acts as a communication bridge between the Observer and Compile. It mainly does the following:
- 1. Add yourself to the attribute subscriber (DEP) during self instantiation
- 2. It must have an update() method
- 3. If you call your own update() method and trigger the callback bound with Compile, you are out of the game.
- Step 4: MVVM, as the entry of data binding, integrates Observer, Compile and Watcher, uses Observer to monitor its model data changes, and uses Compile to parse and Compile template instructions. Finally, Watcher is used to build a communication bridge between Observer and Compile to achieve data change -> view update; View Interactive Changes (INPUT) -> Bidirectional binding effect of data model changes.
Ask for details
- Based on VUE data binding, if the data in data is changed 1000 times per second, will every change be displayed on the page?
The execution of the VUE lifecycle
- First create an instance of vue, vue ();
- When creating the Vue instance, init() is executed, and beforeCreate is called first during init.
- Before creating, data is listened on in data and Vue internal events are initialized. Details are as follows:
- Completed data observation;
- Property and method calculations are completed;
- The callback for the Watch /event event is completed;
- However, the $EL attribute is not visible until the DOM is mounted.
- BeforeMount Completes template compilation. Compile the template from the data object and vUE syntax into HTML, but have not yet rendered the compiled HTML to the page;
- When the template property is inside the instance, use the internal template property and call the render function to render it.
- 2. If no template is found inside the instance, call external HTML (” el “option). The template attribute inside the instance takes precedence over the external one. Render function > template property > external HTML;
- 3. If neither of the first two are satisfied, throw an error.
- Mounted executes the render function to mount the content to the DOM node. Mounted Is a hook function that triggers when HTML is mounted to a page. When Mounted is executed, the entire instance completes the process. Mounted is executed only once during the entire instance.
- BeforeUpdate: When data changes, beforeUpdate is called, then goes through the virtual DOM, and finally updated.
- BeforeDestory is a hook function that destroys all observers, subcomponents, and event listeners before instance destruction.
- The deStoryed instance destroys the executed hook function;
conclusion
- BeforeCreate: initializes part of the forecreate parameters. If the forecreate parameters have the same values and are combined, run the beforeCreate command. El and data objects are undefined and not initialized;
- Created: Initializes Inject, Provide, props, methods, data, computed, and watch, and executes created. Data has it, EL doesn’t;
- BeforeMount: Checks whether there is an EL attribute. If there is an EL attribute, perform dom rendering and run beforeMount. $EL and data are initialized, but the DOM is still a virtual node, and the corresponding data in the DOM has not been replaced.
- Mounted: instantiate Watcher, render DOM, execute mounted; The vue instance is mounted, and the corresponding data in DOM is rendered successfully.
- BeforeUpdate: Execute beforeUpdate during data updates after dom rendering and after mounted hook is executed.
- Updated: Checks the current watcher list to see if the watcher to be updated exists.
- BeforeDestroy: checks whether it has been uninstalled. If it has been uninstalled, return directly. Otherwise, run beforeDestroy.
- Destroyed: to delete all traces of oneself;
Template compilation of vue.js
- Reference: Talk about the principle of Vue2
Const ast = parse(template.trim(), options) // Build the abstract syntax tree optimize(ast, options) Options) // Generate codereturn {
ast,
render: code.render,
staticRenderFns: code.staticRenderFns
}
Copy the code
- It can be divided into three parts
- Convert templates to abstract syntax trees;
- Optimizing abstract syntax tree;
- Generate code from an abstract syntax tree;
- What exactly did you do
- The first part is actually a variety of regees, the matching of left and right open and closed labels and the collection of attributes. In the form of stack, the matching and the replacement of parent nodes are continuously pushed out of the stack. Finally, an object containing children is generated, and children also contains children.
- The second part is based on the first part, according to the node type to find some static nodes and mark;
- The third part is to generate the render function code
- In short, the render function returns VNode (Vue’s virtual DOM node) after converting to AST tree.
- Answer:
- First, compile the template into an AST syntax tree using the Compile compiler. Compile is the return value of createCompiler. CreateCompiler is used to create compilers. Compile is also responsible for merging options.
- The AST then generates the render function by generating (converting the AST syntax tree into a render funtion string). The render returns VNode, which is a virtual DOM node of Vue containing (tag name, child node, text, etc.).
The overall flow of data to view
- At the component level, vue performs a new Watcher;
- New Watcher will first have an evaluation operation, which is to perform a function called render, which may compile the template into a render function, then generate a VNode (virtual DOM), and apply the virtual DOM to the view.
- When the virtual DOM is applied to the view, the expression must be evaluated (e.g. {{message}}, we must fetch its value before rendering), and the corresponding getter is triggered to collect the dependency.
- When the data changes, notify goes to the component-level Watcher, which then evaluates to re-collect the dependencies and re-render the view;
Vue’s computed is different from watch
- Computed means calculating a new attribute and mounting it to the VM (Vue instance), whereas Watch listens for data that already exists and is mounted to the VM, so you can use watch to listen for changes in computed attributes (as well as data and props).
- Computed by nature is a lazy observer with caching properties. A new value is computed only when a dependency changes and a new value is accessed for the first time, whereas watch calls an execution function when the data changes
- In terms of usage scenarios, computed applies to one data affected by multiple data, while Watch applies to one data affecting multiple data.
How does computed data relate to the data being computed
- You need to consider
- How to relate to other attributes;
- How to notify the recalculation of calculated attributes after the change of attributes;
- When initializing data, all attribute data is hijacked using Object.defineProperty;
- Initialize computed, all computed is iterated, and the initComputed function is called for each computed attribute to generate an instance of Watcher;
- Dependency collection takes place in watcher instances;
- For computed computation:
- Assigns the current watcher instance to dep.target;
- Executes the getter method that evaluates the property;
- To read the calculated properties, the corresponding getter methods for those calculated properties are fired. When the calculated property is judged to be a dependency of the calculated property, the dependency is established by adding the calculated property’s Watcher to the message subscriber DEP within the calculated property’s Watcher.
- When done, assign dep. target to null and return the result of the evaluation function.
Seven interactions between VUE components
- 1. The props and $emit
- The parent component passes data to the child component via prop, and the child component passes data to the parent via a $emit trigger event.
- 2. Feature bindings $attrs and $Listeners
- If parent component A has child component B under it, and component B has child component C under it, what if component A wants to pass data to component C? If you continue to use the above method, it will become very complex and not conducive to maintenance; Vue 2.4 started with $listeners and $attrs to fix this problem, allowing messages to be sent from component A to component C.
- 3. Events Bus
- Create a new Vue event bus object and emit events via bus.$ON.
- 4. Dependency injection: provide and inject
- Variables are provided by providers in the parent component and injected by inject in the child component.
- No matter how deep the child component is, as long as inject is invoked, the data in the provider can be injected. Rather than being limited to fetching data only from the prop property of the current parent component, child components can be called as long as the parent component lives.
// Parent component name:"Parent", provide: { for: "demo"}, components:{childOne} // child component name:"childOne", inject: ['for'].data() { return { demo: this.for } }, components: { childtwo } Copy the code
- 5.v-model
- When the parent component passes a value to the child component via the V-model, a prop property of value is automatically passed, and the value of the V-model binding is automatically modified in the child component via this.$emit(‘ input ‘,val)
- Subcomponent references: ref and $refs
- 7. Parent and child indexes: $parent and $children
- 8. Boradcast and Dispatch in VUe1
- This approach was provided in VUe1.0, not in Vue2.0, but many open source software packages themselves, such as MIN UI, Element UI, and iView.
- 9.vuex
What design patterns are used for communication between components?
- There is no answer at present ~~~~ (a question in ali’s telephone interview)
Vuex principle
- Reference: In-depth vuEX principle (PART 1)
- Reference: Vuex source code analysis
- The state of VUEX is realized by means of vUE’s responsive data.
/ / use this.$storeWhen.getters. XXX gets the XXX property, it actually gets store._vm.data.$$stateObject property of the same name getstate () {
return this._vm._data.$$state} resetStoreVM(this, state) store._vm = new Vue({data: {$)$state: state}}) // Because vue data is reactive, so, $$stateIt is also reactive, so when we update state. XXX in a component instance, based on the reactive mechanism of Vue's data, the values of state. XXX of all related components are automatically updated, and the UI is automatically updated as wellCopy the code
- Getters are implemented using vUE’s computed property, computed.
// wrappedGetters method const computed = {}; / / processing gettersforEachValue(wrappedGetters, (fn, key) => {computed[key] = () => fn(store) // Store the getter on computed //this.$storeItem.defineproperty (Store.getters, key, {get: () => Store._vm [key], Enumerable:true})})Copy the code
- The design idea is the same as the VUE central event bus. The implementation of the central event bus, simply speaking, is to create a new VUE object, with the help of the characteristics of the VUE object (EMIT and ON) as the communication bridge of other components, realize the communication between components and data sharing!
Vue-router specifies the difference between hash mode and history mode
- Hash mode urls always have hash signs inside them, and we use this mode by default in development. So when do you use history mode? If the user is concerned about the specification of url, then they need to use history mode, because history mode has no # and is a normal URL suitable for promotion.
- Of course, there are differences in its functions. For example, when we developed the app, we had a sharing page, so the shared page was made with Vue or React. We shared the page with a third party app. There is also a problem with using history mode. If a 404 error occurs when you attempt to refresh a secondary page, you need to work with the backend person to configure apache or Nginx URL redirection to redirect to your home page.
- The hashing mode of the route actually uses the Window to listen for the onHashChange event, which means that if the hash value in your URL changes, the front end can listen and do something in response. Even if the front end doesn’t make an HTTP request it can find a block of code for the page and load it on demand.
- PushState and replaceState can replace a url without refreshing the page. HTTP does not request resources in this path. If the url is refreshed, it will expose the non-existent “goat head”, showing 404. This requires the server to do a bit of tinker by redirecting non-existent path requests to the entry file (index.html).
Custom Components
- Reference: Vue — About custom components
- secondDemoComponent.js
- The index.js: index.js file helps us register all our custom components with Vue.com Ponent, and finally export an object containing the install method to vue.use ().
- Unified import
import global from './components/global/index.js'
Vue.use(global)
Copy the code
Computer network
HTTP status code classification? What is statelessness?
- HTTP stateless
- The server does not save the state of the client, the client must bring its state to the server each time;
- Each request is independent, and < its execution and result > is not directly related to < previous request > and < subsequent request >
- Status code classification
- 1XX indicating information, indicating that the information has been received, continue processing;
- 2XX success: Indicates that the request is successfully received.
- 3XX redirect, which means to complete the request for further operations;
- 4XX client error, request error according to law or request cannot be realized;
- 5XX A server error occurs, indicating that the server fails to implement valid requests.
- For example:
- 200, request successful;
- 302: Redirection;
- 304: Page not modified since last request;
- 400: The client request syntax error.
- 401: Permission problem;
- 403, the server accepts the request but refuses to provide service;
- 404, the requested resource does not exist.
- 500, server internal error;
Differences between HTTP 1.1 and HTTP 2
- HTTP/2 is in binary format rather than text format
- Binary protocols parse more efficiently, are more compact “on line” and, more importantly, have fewer errors than text protocols like HTTP/1.x.
- HTTP/2 is fully multiplexed, not ordered and blocking — only one connection is required to achieve parallelism
- HTTP/1.x has a problem with head-of-line blocking, which means that a connection is blocking one request at a time. HTTP/1.1 has tried pipelining to solve this problem, but it doesn’t work very well (a large or slow response can block requests that come after it). In addition, because the network medium (intermediary) and server can not support the pipeline, resulting in the deployment of difficulties. Multiplexing can solve these problems well because it can handle multiple message requests and responses at the same time. You can even mix one message with another in transit. So the client only needs a connection to load a page.
- Using header compression, HTTP/2 reduces overhead
- HTTP2 uses gZIP and COMPRESS to compress the header and send it. The client and server maintain a header table in which all fields are stored
- HTTP/2 allows the server to actively “push” responses into the client cache
- HTTP2 supports actively pushing content to clients without their requested permission
The difference between POST and GET requests
The basic difference between
- Application: When the method property of the form is set to POST, it sends a POST request and everything else is a GET request (AJAX is not considered).
- Parameter transmission mode: Get request parameters are sent through the URL address, AND POST request parameters are sent through the request body.
- Security: Get request parameters are sent directly through the URL address. The parameters are visible in the address bar, which is insecure. Post requests send request parameters through the request body. The parameters are not visible in the address bar and are relatively secure.
- The LENGTH of the URL address is limited to 255 bytes. Therefore, a GET request cannot send too many parameters. A POST request sends parameters through the request body.
- The size and length of the data submitted by the Get method are not limited. Internet Explorer has a maximum length of 2048 characters on the URL (5.7 Note: Browsers have restrictions on request headers).
Senior difference
- The essence of GET is “GET”, while the essence of POST is “give”. The content of a GET is cached by the browser, but the data of a POST is not.
- 1. Get generates a TCP packet, one in the request header and one in the request body. Post generates two TCP packets;
- 2. Get is done once in a single request. Post is faster and more efficient than POST because some browsers (except Firefox) require two messages to be sent.
What is cross-domain? What are the methods and principles to solve cross-domain?
- 1. Different sources are cross-domain
- 2. The same-origin policy is a security policy of the browser
- 3. If the protocol, domain name, and port number are identical, they are the same as each other. If there is one difference, they are cross-domain
- 4. Exceptions: Ajax can only parse strings when determining domain names, resulting in (localhost and 127.0.0.1) being seen as cross-domain requests
- 5. Cors and JSONP are usually used to solve cross-domain problems
- 6.JSONP
- 1.JSONP is a skill, not a new technology
- 2. The SRC attribute of scIRPT tag is not restricted by cross domain
- 3. Cross-domain solution:
- 1. Browser side: dynamically generate script tag, define callback function in advance, add SRC attribute to specify request address when appropriate.
- 2. Server-side: The background receives the callback function, including the data in the handle of the callback function call, and returns it together.
- 3. Only GET requests are supported
function jsonp({url,params,callback}){
returnNew Promise((resolve,reject)=>{// Create srciptlet script = document.createElement("script")
window[callback] = function{(data) resolve (data). The document body. RemoveChild (script)} / / parameter to reformat params = {... params,callback} // wd=b&callback=showlet arrs = []
for(let key in params){
arrs.push(`${key}=${params[key]}')} // Script. SRC = '${url}?${arrs.join('&')}` / / srcipt inserted into the document. The body. The appendChild (script)})} the json ({url:'http://localhost:3000/say',
params: { wd: 'Iloveyou' },
callback: 'show'
}).then(data=>{
console.log(databufen)
})
Copy the code
- 7.CORS
- 1. Do nothing on the browser side;
- 2. Set the response header to access-Control-allow-origin on the server
- 3. Cors is a technology that essentially allows ajax engines to cross domains
- 4. Both GET and POST requests are supported
Why can CROS solve cross-domain problems? // TODO
- Related to the first option request sent;
- Across domains, the browser intercepts Ajax requests and adds Origin to the HTTP header.
Browser problems
Browser cache
- Front-end optimization: Introduction to browser caching technology
The client has two types of storage
SessionStorage is used differently from localStorage
- Life cycle:
- The localStorage (localStorage) life cycle is permanent, which means that localStorage information will remain forever unless the user displays it on the browser-provided UI and clears it.
- The sessionStorage life cycle is the current window or TAB. Once the window or TAB is closed, all data stored through sessionStorage is cleared.
- Different scopes: Different browsers cannot share information in localStorage or sessionStorage.
- Different pages in the same browser can share the same localStorage (pages belong to the same domain name, protocol, host, and port).
- SessionStorage information cannot be shared between different pages or tabs.
- As long as localStorage uses the same protocol, host name, and port, it can read/modify the same localStorage data.
- SessionStorage is more stringent than localStorage. In addition to protocol, host name, port, sessionStorage also requires the same window (that is, the browser TAB).
- Storage size: localStorage and sessionStorage data size is generally: 5MB;
- Storage location: Both localStorage and sessionStorage are stored in the client and do not interact with the server.
- Store content types: localStorage and sessionStorage can only store strings. For complex objects, use stringify and Parse for JSON objects provided by ECMAScript.
- LocalStorage: window.localstorage; SessionStorage: window. SessionStorage;
- Application scenarios: localStoragese: Used for long-term login (+ check whether a user has logged in). It is suitable for storing data locally for a long time. SessionStorage: one-time login with sensitive accounts.
What criteria are used for localStorage and cookie selection
- It has to do with the server side,
- Cookie each time send request is by default with, but things exist in localstorage is not with, need to write in;
Why is the lifetime of a session in a single session?
- There is no detailed answer ~~ at that time, the answer is as follows:
- Session is the server; It is used to match the cookie of the client. The sessionID is a new session every time, but the session is always present.
Cookie Storage is different from Web Storage
- LocalStorage and sessionStorage as the products of the new era, compared with the cookie of the old era has its huge advantages. There are three advantages:
- The first is the amount of data that can be stored, cookie can store up to 4KB of data, while localStorage and sessionStorage can store up to 5Mb, which is the standard supported by all major browsers at present.
- Second, in terms of function, cookies can only store String data. In the past, to store user data locally, data needs to be spliced into strings and then stored in cookies. It is also troublesome to fetch data. Access is a hassle! LocalStorage and sessionStorage not only support the traditional String type, but also can store JSON objects, access data are convenient, JSON superiority is not described, localStorage and sessionStorage is undoubtedly more modern;
- Third, cookie is indispensable. Cookie’s function is to interact with the server, and it exists as part of the HTTP specification. Web storage is just for local ‘storage’ and born;
- Fourth, on the semantic level, localStorage and sessionStorage syntax is more elegant and simple.
// Set cookie: document.cookie ='key=value'; Get cookies: document. Cookies; Delete cookie: document.cookie ="key=value; max-age=0"; Set max-age storage period: document.cookie ="key=value; max-age=1000"; // 1000 seconds // Web storage Saves datasetItem(key,value) Reads data getItem(key) Deletes a single data removeItem(key) Clears all data clearItem() Retrieves data index Key (index)Copy the code
Browser kernel? And common browser compatibility issues
- Browser kernel
- Trident(IE kernel) : Represented by Internet Explorer, IE6, IE7, IE8 (Trident 4.0), IE9 (Trident 5.0), and IE10 (Trident 6.0).
- Gecko(Firefox kernel) : The Gecko kernel is also the most popular browser in Firefox, so it is sometimes referred to as the Firefox kernel.
- Webkit (Safari kernel,Chrome kernel prototype, open source) : This is Apple’s own kernel and the kernel used by Apple’s Safari browser. Apple Safari will also use it.
- Presto (pre-Opera kernel) (deprecated) : Kernel used in Opera12.17 and earlier, now discontinued and deprecated. Opera has switched to Google Chrome’s Blink kernel.
Common browser compatibility issues
Compatibility issues in HTML
- The default external and internal patches for different browser labels are different.
- Scenario: Write a few tags randomly, without style control, the margin and padding of each tag will be very different.
- *{margin:0; padding:0; };
- After the block property tag float, the margin in IE6 is displayed larger than the set margin in the case of horizontal margin.
- Scenario: A common symptom is that the last block in IE6 is pushed to the next line;
- Solution: Add display:inline; Convert it to an inline property
- The Z-index in Internet Explorer 6 is invalid
- Scenario: If the z-index of the parent element of an element is set to 1, then the z-index of the child element will be invalid, and the hierarchy of the child element will inherit the setting of the parent element, causing some level adjustment bugs.
- Reason: Z-index works only if the element’s position attribute is relative, absolute, or fixed.
- 1. Position :relative; position:absolute; 2. Remove float; 3. Add position attributes (relative, absolute, etc.) to float elements.
- When writing the style of the A tag, the style has no effect, in fact, the style is overwritten
- The correct order of a tags should be: Link/visited/hover/active
- 24 bit PNG images, not compatible with transparent background in IE6
- Solution: Use PNG transparent images, but note that 24-bit PNG images are not supported in IE6. There are two solutions:
- Use 8-bit PNG images;
- Prepare a special set of images for IE6
- Solution: Use PNG transparent images, but note that 24-bit PNG images are not supported in IE6. There are two solutions:
Js compatibility issues in different browsers
- Compatibility of event listeners;
- IE does not support addEventListener;
- Solution: Use attachEvent for IE
var addHandler = function(el, type, handler, args) {
if (el.addEventListener) {
el.addEventListener(type, handler, false);
} else if (el.attachEvent) {
el.attachEvent('on' + type, handler);
} else {
el['on' + type] = handler; }}; var removeHandler =function(el, type, handler, args) {
if (el.removeEventListener) {
el.removeEventListener(type, handler, false);
} else if (el.detachEvent) {
el.detachEvent('on' + type, handler);
} else {
el['on' + type] = null; }};Copy the code
- Compatible with event.target, the DOM element that raises the event.
- IE6789 does not support event. Target.
- Event.srcelement;
/ / here is compatible with writing target = event. The target | | event. The srcElement;Copy the code
- Prevents system default compatibility
- IE6789 does not support Event.preventDefault;
// Event.preventdefault? event.preventDefault() : (event.returnValue =false);
Copy the code
- Compatibility to prevent event bubbling
- IE6789 does not support Event. StopPropagation.
// Event.stopPropagation? event.stopPropagation() : (event.cancelBubble =false);
Copy the code
The business problem
360 search images of this waterfall flow layout
Lazy loading of images
- The high bar method: getBoundingClientRect() gets the distance to the top of the element directly.
- Reason: We often have to put many images on a page, performance is a big problem, loading all images at once can be very slow, so loading them when you need a preview is a good solution.
- You can also create an image by passing the url to the image when it appears in the viewable area of the browser. The image is wrapped in a container, such as li or div. The url of the image is stored in the data-src attribute of the container.
- Process:
- Add a custom attribute to the element of the img tag, such as data-src, with the true SRC set to null;
- Determine the image’s distance from the top of the page is less than the browser’s scrolling distance plus the viewable area height, i.e. load it when it appears in the viewable area.
/ / h = window. The innerHeight -- visual area height / / s = document. DocumentElement. The scrollTop | | document. The body. The scrollTop - rolling distance; GetTop (imgs[I]) getBoundingClientRect() to get the height of the current image from the topif(h + s > getTop(imgs[i]) && ! imgs[i].getAttribute('src')) Copy the code
- Loading pictures
imgs[i].src = imgs[i].getAttribute('data-src');
- Finally, assign the page scroll function to the element window.onload and wait until all elements are loaded. This is important!
window.onload = window.onscroll = function() {// lazyLoad(imgs); }Copy the code
Problems encountered in the project
Problems with using GET in Ajax
- Problem 1. Cache: When the URL is the same each time, the client directly reads the content in the local cache, even if the background data changes, the foreground will not change;
- Solution: In? Num = [random number math.random ()] or num= [timestamp new Date().gettime ()], ‘1.php? Username =”May”& “+num”
Performance optimization
- Sprite figure
- Reduce DOM manipulation: event broker, fragment;
- Compressed JS and CSS, HTML;
Mainstream framework problem
Vue, React and Angular are different
- Borrow Angular templates and data binding techniques;
- React componentization and virtual DOM technology;
- Under the volume, high operation efficiency, simple coding, PC/ mobile terminal development is suitable;
- It focuses solely on the UI itself and can easily introduce vUE plug-ins and other third library development projects;
Coding questions (Bytedance video interview)
- Define a Queue that prints 1 every 1000 seconds on the first call, 2 every 2000 seconds on the second call… Finally, run() can be called;
new Queue()
.task(() => {
console.log(1)
}, 1000) .task(() => {
console.log(2)
}, 2000) .task(() => {
console.log(3)
}, 3000) .run()
Copy the code
- Define a function, summation function, that can be called countless times, and call valueOf at the end to display the final summation result;
sum(1)(2)(3)(4).valueOf()
Copy the code
- Step 1: Promise+ AXIos After writing, request to implement 5 requests each time on this basis (no ~~~);
// Promise+ AXIos implement concurrent requests // Implement concurrent requests 5 times // first answerfunction getRequest() {return axios.get(url)
};
function postrequest() {return axios.post(url)
};
axios.all([getRequest(),postrequest()])
.then()
Copy the code
- Some of them were asked in the interview, and some of them were likely to be asked when reading the article. Some have the answer, some have no answer, there are two reasons for no answer: one is a common question, I hope to be free to sort out the higher case of the answer; The other one is that it has not been solved yet, but we will study and give answers after the end of the interview. You are especially welcome to give answers or ideas on these questions in the comments.
- Some students said in the comments that the feeling question is relatively easy, I want to say, when I see a lot of questions, I also feel this way, but, maybe later will ask you deeper.
- How does new or Instanceof work? The second question is: please write a new or instanceof; Another example is the difference between cookie and session. The second question is: from the perspective of the server, what is the difference between cookie and session? Then: why is the session only valid for a single call, and is it a field on the server? Or what on the server? Again, what do you know about VUE component communication? The second question is: what are the design patterns used for component communication? Finally, have you used NPM and YARN? Second question: how do you resolve version dependence of NPM packages? What is the principle of package-lock?
- What I want to say is that words can present is very simple, but if you want to go deep, there is no bottom line. These great purposes are to have a look before the interview. Engineers must always have the capital to leave in their work, know what it is and know why! In addition, before the interview must be prepared, at least a week ~~~~