Part I. HTML
1. Briefly describe your understanding of HTML semantics?
Doing the right thing with the right tags. The html semanticization allows the content of the page to be structured and structured more clearly for the browser,Internet search engineparsing; even in the absence of styled CSS, it resolves to anfile formatdisplay and is easy to read; search enginereptileIt also relies on HTML tags to determine the context and weight of each keyword, which is good for SEO; it makes it easier for people who read the source code to chunk the site, making it easier to read and maintain and understand.
2. What is the difference between the title and alt attributes on a tag?
alt is forInternet search engineRecognition, alternative text when the image can not be displayed; title is the comment information about the element, mainly for the user to interpret. The title text is displayed when the mouse is placed over the text or image. (Because IE is not standardized.) In IE, alt takes over the role of title and becomes a textual hint. When defining the img object, write alt and title attributes to ensure that it works in all browsers.
3. advantages and disadvantages of iframe?
Pros:
Resolve slow loading third-party content such as icons and advertisements
Security sandbox
Loading scripts in parallel
Drawbacks:
The iframe blocks the Onload event of the main page.
It takes time to load even if the content is empty.
No semantics.
4. href vs. src?
href (Hypertext Reference) specifies the location of a web resource, thereby defining a link or relationship between the current element or the current document and the desired anchor or resource defined by the current attribute. (The purpose is not to reference the resource, but to establish a link so that the current tag can link to the target address.)
src source (abbreviation), pointing to the location of an external resource, the content of which will be applied to the current tag location in the document.
The difference between href and src
1, different types of requested resources: href points to the location of the network resource to establish a connection between the current element (anchor) or the current document (link). In the request src resource will point to the resource will be downloaded and applied to the document, such asJavaScript Script, img image;
2, the role of different results: href is used to establish a link between the current document and reference resources; src is used to replace the current content;
3, the browser parses differently: when the browser parses the src , it will pause the download and processing of other resources until the resource is loaded, compiled, executed, images and frames, etc., similar to the resources pointed to apply to the current content. This is why it is recommended to put js scripts at the bottom of the page instead of in the header.
Part II. CSS
1. What about the CSS box model?
There are two kinds of box model, IE box model and W3C box model; box model: content, padding, margin, border; difference: IE content part of the border and padding into the calculation.
2. css selector priority?
!important > in-line styles (weight 1000) > ID selectors (weight 100) > class selectors (weight 10) > tags (weight 1) > wildcards > inheritance > browser default attributes
3. How many ways are there to center vertically?
single-line text: line-height = height photograph: vertical-align: middle; absolute localization: top: 50%;left: 50%;transform: translate(-50%, -50%); flex: display:flex;margin:auto
4. Briefly explain the difference and usage of CSS link and @import?
link is an XHTML tag, besides loading CSS, it can also define other matters such as RSS; @import belongs to the scope of CSS, it can only load CSS. When link references CSS, it will be loaded at the same time when the page is loaded; @import needs to be loaded after the page is fully loaded. link is an XHTML tag, no compatibility issues; @import was introduced in CSS2.1, and is not supported by lower browsers. link supports using Javascript to control the DOM to change the style; @import does not.
5. what is the difference between rgba and opacity for transparency?
opacity inherits the opacity attribute of the parent element, while descendants of elements with the RGBA setting do not inherit the opacity attribute.
6. What is the difference between display:none and visibility:hidden?
display:none hides the corresponding element, no space is allocated for it in the document layout, and the elements on each side of it are merged as if it never existed. visibility:hidden hides the corresponding element, but retains its original space in the document layout.
7. What are the values of position, relative and absolute, relative to?
relative: relative positioning, relative to its own position in the normal document flow. absolute: Generates absolute positioning, relative to the most recent parent element whose positioning is not static. fixed: (not supported by older versions of IE) generates absolute positioning, relative to the browser window or frame. static:Default, no positioning, element appears in normal document flow. sticky:Generates sticky positioned elements, with the container's position calculated from the normal document flow.
8. Draw a 0.5px line?
The test is about css3 transforms.
height: 1px; transform: scale(0.5); 12
9. What is the meaning and usage of calc, support, media?
@support is mainly used to detect whether the browser supports a certain CSS property, in fact, it is a conditional judgment, if it supports a certain property, you can write a set of styles, if it does not support a certain property, you can also provide another set of styles as a replacement.
The calc() function is used to dynamically calculate length values. The calc() function supports "+", "-", "*", "/" operations;
@media query, you can define different styles for different media types.
10. What does 1rem, 1em, 1vh, 1px mean?
rem rem is all the length relative to the root element element. The usual practice is to set a font size for the html element, and then the other elements are rem in length units.
em The em of a child element's font-size is relative to the parent element's font-size. The em of an element's width/height/padding/margin is relative to the element's font-size.
vw/vh is the full name of Viewport Width and Viewport Height, the width and height of the window, which is equivalent to 1% of the screen width and height, however, % is more appropriate when dealing with width, and vh is better when dealing with height.
px px Pixel (Pixel). Relative unit of length. The pixel px is relative to the monitor screen resolution. Typical computer resolutions are {19201024} and other different resolutions 19201024 The former is the width of the screen totaling 1920 pixels, while the latter is the height of 1024 pixels.
11. Draw a triangle?
This is a simple css test, usually use the component library at the same time, do not forget the native css
.a { width: 0; height: 0; border-width: 100px; border-style: solid; border-color: transparent #0099CC transparent transparent; transform: rotate(90deg); /* Rotate 90° clockwise */ } <div class="a"></div> 123456789
Third, HTML / CSS mixed chapter
1. What new features have been added to HTML5 and CSS3?
HTML5
New semantic tags
article Stand-alone content.
aside Sidebar.
header header.
nav navigation.
section A section in a document.
footer The footer of the page.
Canvas API
Geolocation APIs
Local offline storage localStorage stores data for a long time, data is not lost after the browser is closed; sessionStorage data is automatically deleted after the browser is closed.
New technologies webworker, websocket, Geolocation
Drag and drop APIs
Audio, Video API(audio,video)
Form controls, calendar, date, time, email, url, searc
CSS3
2d, 3d transformations
Transition, animation
Media Enquiry
New units (rem, vw, vh, etc.)
rounded corners (border-radius), shadow (box-shadow), text-shadow, gradient, transform 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, scale, position, skew
rgba
2. What is BFC?
BFC is Block Formatting Contexts, which belongs to the normal flow, i.e., elements are laid out according to their sequential position in the HTML in a top-down layout, in which the elements are arranged horizontally in the line until the line is full and then the line is changed, and the block-level elements are rendered as a complete new line, and all elements are positioned in the normal flow by default, unless otherwise specified. Unless otherwise specified, all elements are positioned in the normal flow by default, which means that the position of an element in the normal flow is determined by its position in the HTML document. The BFC can be thought of as a big, closed box, where the elements inside the box, no matter how much they flop around, don't affect the outside. The BFC feature is triggered when an element meets one of the following conditions
body Root element
Floating elements: float values other than none.
Absolute positioning elements: position (absolute, fixed)
display because of inline-block、table-cells、flex
overflow values other than visible (hidden, auto, scroll)
3. Common compatibility issues?
Browsers have different margins and padding by default. The solution is to add a global *{margin:0;padding:0;} to standardize it.
Chrome will force text smaller than 12px to display at 12px by default, which can be solved by adding the CSS property -webkit-text-size-adjust: none;.
Part IV. JS
1. JS data types ?
The data type consists of two main parts:
Basic data types: Undefined, Null, Boolean, Number, and String.
Reference data types: Object (including Object, Array, Function)
ECMAScript 2015 New: Symbol (unique and immutable datatype after creation )
2. What are some ways to determine what type a value is?
typeof operator
instanceof operator
methodologies
3. the difference between null and undefined?
null means that an object is defined with a "null" value; undefined means that the value does not exist. (1) When a variable is declared but not assigned a value, it is undefined. (2) When a function is called with a parameter that should be supplied but is not, the parameter is undefined. (3) When a property of an object is not assigned a value, the value of the property is undefined. (4) When a function does not return a value, it returns undefined by default.
4. How do you determine if a variable arr is an array (typeof doesn't work for this question)?
arr instanceof Array == Array (arr) == ‘[Object Array]’
5. What is the difference between "===" and "=="?
==, it returns true if and only if the two operators are equal, i.e. it does not check the data type ===, it returns true only if the operators are equal without the need for type conversion, which requires checking the data type
6. "What does eval do?
Its function is to parse the corresponding string into JS code and run it; eval should be avoided, it's unsafe and very performance intensive (2 times, one for parsing into a js statement and one for executing it).
7. What are the characteristics of the arrow function?
Creating functions without the function keyword Omitting the return keyword Changing what this points to
8. What is the difference between var, let, and const?
var There is variable lifting. let can only be accessed in block-level scopes. const is used to define constants, which must be initialized and cannot be modified (object specific)
9. What exactly does the new operator do?
1. An empty object is created and referenced by this variable, which also inherits the function's prototype. 2. Properties and methods are added to the object referenced by this. 3. The newly created object is referenced by this, and this is implicitly returned at the end.
10. What do you know about JSON?
JSON (JavaScript Object Notation) is a lightweight data exchange format. It is based on a subset of JavaScript. Simple data format, easy to read and write, small bandwidth consumption {'age':'12', 'name':'back '}
11. and innerHTML?
Only the whole page can be redrawn innerHTML can redraw part of the page
12. ajax process?
(1) Create an XMLHttpRequest object, that is, create an asynchronous call object. (2) create a new HTTP request, and specify the HTTP request method, URL and authentication information. (3) Set the function that responds to changes in the state of the HTTP request. (4) Send HTTP request. (5) Get the data returned by the asynchronous call. (6) Using JavaScript and DOM to achieve local refresh .
13. Please explain JavaScript's homology policy?
Concept:Same-origin policy is a policy for client-side scripts (especially Netscape Navigator 2.0, which aims to prevent a document or script from being loaded from several different sources. Same-origin policy here means: the same protocol, domain name, port, same-origin policy is a security protocol. It means that a script can only read the properties of windows and documents from the same source.
14. Introduce closures and common closure scenarios?
A closure is a function that has access to a variable in the scope of another function. A common way to create a closure is to create another function inside of a function
The use of closures is mainly for the design of private methods and variables, the advantage of closures is that they can avoid the pollution of variables, the disadvantage is that the closure will be resident in memory, which will increase memory usage, improper use can easily cause memory leaks. In js, function that is closure, only function will produce the concept of scope.
Closures have three properties:
function nesting function
Functions can refer to external parameters and variables internally
Parameters and variables are not reclaimed by the garbage collection mechanism
Application scenarios, methods for setting private variables
Exclusion scenario: the function that returns the closure is a very large function
The disadvantage of closures is that they are memory-resident, which increases memory usage and can cause memory leaks when used improperly
15. javascript's memory (garbage) collection mechanism?
The garbage collector finds memory that is no longer in use and frees it every once in a while.
General useMark and sweep methods, when a variable enters the environment it is marked as entering the environment, and when it leaves the environment it is marked as leaving the environment The garbage collector tags all variables stored in memory at runtime, and then removes variables in the environment and variables referenced by variables in the environment (closures), and the variables that are still tagged are the ones that are to be deleted when this is done
there areThe reference counting method.In low versions of IE, memory leaks often occur, often due to the use of reference counting for garbage collection. The strategy of reference counting is to keep track of the number of times each value has been used. When a variable is declared and a reference type is assigned to it, the number of times this value is referenced is increased by one, and if the value of the variable is changed to another, the number of times this value is referenced is decreased by one, and when the number of times this value is referenced reaches zero, it means that there is no variable being used, and that this value can't be accessed, and so the space occupied by the variable is reclaimed, so that the garbage collector will clean up the space occupied by the value that is zero at runtime. The garbage collector will clean up the space occupied by the value with a reference count of 0 at runtime.
In IE, although JavaScript objects are garbage collected by marking them for removal, BOM and DOM objects are garbage collected by reference counting, which means that circular references occur whenever the BOM and DOM are involved.
16. JavaScript prototypes, prototype chains ? What are the characteristics ?
Any object that hasproto Implicit prototype, equal to the prototype of the constructor.
const obj = {} obj.__proto__ === // true 12
Any function has a prototype showing that a prototype is equivalent to a prototype object (that is, a normal object containing public properties) * (the exception is functions constructed via methods, which do not have a prototype attribute)
function Person () {} = prototype object === Person // true const person1 = new Person person1.__proto__ === // true == Person // true 1234567
The object also has a constructor attribute that points to the constructor (== Person)
The prototype chain is dependent on theproto, finding an attribute follows theproto The prototype chain looks up until it is found.
specialty
// The prototype chain ends up at null .__proto__ === null // true obj.__proto__.__proto__ === null // true 123
Each object will be initialized in its internal properties, that is, prototype (prototype), when we access the properties of an object, if the object does not exist within the property, then he will go to the prototype to find the property, the prototype will have its own prototype, so this has been looking for, that is, we are usually refer to the concept of prototype chaining.
Relationship: = instance.proto
Features: JavaScript objects are passed by reference, and each new object entity we create does not have a copy of the prototype that belongs to it. When we modify the prototype, the objects associated with it inherit the change.
17. write sum from 1 to 100 recursively in js?
function add(num1, num2) { const num = num1 + num2; if(num2 === 100) { return num; } else { return add(num, num2 + 1) } } var sum = add(1, 2); 123456789
18. Event queues (macrotasks microtasks)
It can be divided into micro task (micro task) queue and macro task (macro task) queue.
Microtasks are generally executed before macrotasks, and there is only one queue of microtasks, whereas there may be more than one queue of macrotasks.. Also our common events such as clicks and keyboards belong to macro tasks.
Below we look at common macro tasks and common micro tasks.
Common Macro Tasks:
-
setTimeout()
-
setInterval()
-
setImmediate()
Common microtasks:
-
()、()
-
new MutaionObserver()
-
()
The essential difference between microtasks and macrotasks.
-
Macro-mandate characteristics: There are explicit asynchronous tasks to be performed and callbacks to be made; other asynchronous thread support is required.
-
Microtask features: There are no explicit asynchronous tasks to perform, only callbacks; no other asynchronous thread support is needed.
setTimeout(function () { ("1"); }, 0); async function async1() { ("2"); const data = await async2(); ("3"); return data; } async function async2() { return new Promise((resolve) => { ("4"); resolve("Results of async2."); }).then((data) => { ("5"); return data; }); } async1().then((data) => { ("6"); (data); }); new Promise(function (resolve) { ("7"); resolve() }).then(function () { ("8"); }); // 2 4 7 5 8 3 6 Results of async2 1 123456789101112131415161718192021222324252627282930
19. async/await
async is a function that is executed asynchronously and implicitly returns a Promise as a result. It is syntactic sugar for Generator functions and improves upon them.Improvements:
-
The built-in actuator eliminates the need to manually execute the next() method.
-
Better Semantics
-
Broader applicability: The co module convention is that the yield command can only be followed by a Thunk function or a Promise object, whereas the await command of an async function can be followed by a Promise object and a primitive type of value (numeric, string, and boolean, but this is automatically converted to an instantly resolved Promise object).
-
The return value is a Promise, which is more convenient than the Iterator object returned by the Generator function, and can be called directly using the then() method.
-
async implicitly returns the Promise as a function of the result, then it can be simply understood that await generates a microtask (it's a microtask) when the execution of the function following await finishes.
20. JavaScript is single-threaded, browsers are multi-processed
-
A rendering process is created every time a new web page is opened
-
The rendering process is multithreaded
-
GUI Renderer Thread for Page Rendering
-
the JavaScript engine thread responsible for JavaScript execution.
-
The event-triggering thread responsible for the browser's event loop; note that this is not part of the JavaScript engine thread.
-
Timing trigger thread responsible for the timer, intervals less than 4ms in setTimeout are counted as 4ms
-
Asynchronous http request thread responsible for XMLHttpRequest
-
GUI rendering threads and JavaScript engine threads are mutually exclusive
-
Single-threaded JavaScript is used to avoid DOM rendering conflicts. web worker supports multi-threading, but web worker can't access window objects, document objects and so on.
V. Part Vue
1. Tell us about your understanding of the MVVM development model?
MVVM is divided into Model, View, ViewModel three. Model represents the data model, data and business logic are defined in the Model layer; View represents the UI view, responsible for displaying data; ViewModel is responsible for listening to changes in the data in the Model and controlling the update of the view to deal with user interactions; Model and View do not have a direct connection, but through the ViewModel to contact, there is a two-way data binding connection between Model and ViewModel. Model and View are not directly related, but are connected through ViewModel, and there is a two-way data binding connection between Model and ViewModel. Therefore, when the data in the Model changes, it will trigger the refresh of the View layer, and the data changed in the View due to user interactions will also be synchronized in the Model. This pattern achieves automatic synchronization of data between Model and View, so developers only need to focus on maintaining the data, and do not need to manipulate the dom.
2. What is the difference between v-if and v-show?
The v-if is true conditional rendering and will control whether this DOM node exists or not. This is because it will ensure that event listeners and subcomponents within the conditional block are appropriately destroyed and rebuilt during the switch; it's also inert: if the condition is false during the initial rendering, nothing is done - the rendering of the conditional block won't begin until the condition becomes true for the first time.
v-show is much simpler - the element is always rendered regardless of the initial condition, and is simply toggled based on the CSS "display" property.
When we need to toggle the show/hide of an element frequently, using v-show will save more performance overhead; when we only need to show or hide it once, it makes more sense to use v-if.
3. Have you used Vuex?
Vuex is a state management model developed specifically for applications. At the heart of every Vuex application is a store. A "store" is basically a container that contains most of the state in your application.
(1) The Vuex state store is responsive. When a Vue component reads state from the store, if the state in the store changes, the corresponding component will be efficiently updated accordingly.
(2) The only way to change state in the store is to explicitly commit mutation, which makes it easy to keep track of every change in state.
The main modules include the following:
State => Basic data, defines the data structure of the application state, where the default initial state can be set.
Getter => Derived from basic data that allows a component to get data from the Store, the mapGetters helper function simply maps the getter from the store to a local computed property.
Mutation => is the only way to change the state in the store and must be a synchronized function.
Action => acts like a decorator, wrapping mutations so that they can be asynchronous. Used to commit mutations instead of changing state directly, and can contain arbitrary asynchronous actions.
Module => A modular Vuex that allows a single Store to be split into multiple stores and kept in a single state tree at the same time.
4. What is your understanding of the SPA single page and what are its advantages and disadvantages?
SPA (single-page application) only in the Web page initialization to load the appropriate HTML, JavaScript and CSS. once the page > surface loading is complete, SPA will not be due to user operations and page reload or jump; instead, the use of routing mechanisms to achieve > HTML content transformation, UI and user interaction to avoid reloading the page. Instead, it utilizes a routing mechanism to transform the HTML content and the UI to interact with the user, avoiding page reloads.
Advantages: good user experience, fast, content changes do not need to reload the entire page, avoiding unnecessary jumps and repeated rendering; based on the above point, SPA relatively low pressure on the server; front and back end responsibilities are separated, the structure is clear, the front-end interaction logic, the back-end is responsible for data processing;
Disadvantages: Initial loading time-consuming: In order to realize the function and display effect of the single-page Web application, you need to load the page when the JavaScript, CSS unified & gt; load, some pages on demand; forward and backward routing management: Because the single-page application displays all the content in a page, so you can not use the browser's forward and backward function, all & gt; all the page switching Need to build their own stack management; SEO difficulty: because all the content is displayed in a page dynamic replacement, so it has a natural disadvantage in SEO.
5. How are Class and Style dynamically bound?
Classes can be bound dynamically using object syntax and array syntax:
-
Object syntax:
<div v-bind:class="{ active: isActive, 'text-danger': hasError }"></div> data: { isActive: true, hasError: false } 12345
-
Array syntax:
<div v-bind:class="[isActive ? activeClass : '', errorClass]"></div> data: { activeClass: 'active', errorClass: 'text-danger' } 12345
Style can also be bound dynamically using object syntax and array syntax:
-
Object syntax:
<div v-bind:style="{ color: activeColor, fontSize: fontSize + 'px' }"></div> data: { activeColor: 'red', fontSize: 30 } 12345
-
Array syntax:
<div v-bind:style="[styleColor, styleSize]"></div> data: { styleColor: { color: 'red' }, styleSize:{ fontSize:'23px' } } 123456789
6. How to understand Vue's unidirectional data flow?
All props make a unidirectional downward binding between their parent and child props: updates to the parent prop flow down to the child component, but not vice versa. This prevents accidental changes to the state of the parent component from the child component, which can make the flow of data in your application hard to understand. Additionally, every time an update occurs to the parent component, all props in the child component will be refreshed to the latest value. This means that you shouldn't change a prop inside a child component, and if you do, Vue will issue a warning in the browser's console. If a child component wants to change it, it can only do so by sending a custom event via $emit, which the parent component receives and then modifies.
7. What is the difference between computed and watch and how are they used?
computed: is a computed attribute that depends on the values of other attributes, and the value of computed is cached so that it is only recalculated when the value of the attribute on which it depends is changed and the value of computed is retrieved the next time it is retrieved;
watch: more of an "observation" role, similar to some of the data listening callbacks, whenever listening to the data changes will execute the callback for subsequent operations;
Utilization Scenario:
When we need to perform numerical calculations that depend on other data, we should use computed because we can take advantage of computed's caching feature to avoid having to recalculate the value every time we get it;
We should use watch when we need to perform asynchronous or high overhead operations when the data changes, using the watch option allows us to perform asynchronous operations ( access an API), limit how often we perform that operation, and set intermediate state before we get the final result. These are all things that the compute attribute cannot do.
8. Can Vue detect changes when an array item is assigned a value directly?
Due to JavaScript limitations, Vue cannot detect changes to the following arrays:
When you set an array item directly using an index, for example:
[indexOfItem] = newValue
When you modify the length of an array. for example:
= newLength
-
To solve the first problem, Vue provides the following actions:
// (, indexOfItem, newValue) // vm.$set, an alias for the vm.$set(, indexOfItem, newValue) // (indexOfItem, 1, newValue) 123456
-
To solve the second problem, Vue provides the following action methods:
// (newLength) 12
9. What is your understanding of the Vue lifecycle?
-
What is the life cycle?
Vue instances have a complete lifecycle, that is, a series of processes from the beginning of creation, initializing data, compiling templates, mounting Dom -> rendering, updating -> rendering, uninstalling, and so on, we call this the Vue lifecycle.
-
Role of each life cycle
life cycle descriptive beforeCreate When the component instance is created, before the component's properties take effect created The component instance is fully created and properties are bound, but the real dom has not been generated and $el is not available yet. beforeMount Called before the start of the mount: the associated render function is called for the first time. mounted The hook is called after el is replaced by the newly created vm.$el and mounted on the instance beforeUpdate Called before the component data is updated, occurs before the virtual DOM is patched updated After the component data has been updated activited keep-alive is exclusive and is called when the component is activated. deadctivated keep-alive is exclusive and is called when the component is destroyed. beforeDestory Called before component destruction destoryed Called after component destruction
10. What is the order of execution of Vue's parent and child lifecycle hook functions?
Vue's parent and child component lifecycle hook function execution order can be categorized into the following 4 parts:
Loading the rendering process : father beforeCreate -> father created -> father beforeMount -> small thing beforeCreate -> small thing created -> small thing beforeMount -> small thing mounted -> father mounted
Child component update process : parent beforeUpdate -> child beforeUpdate -> child updated -> parent updated
Parent component update process : parent beforeUpdate -> parent updated
Destruction process : father beforeDestroy -> small thing beforeDestroy -> small thing destroyed -> father destroyed
11. Can a parent component listen to the life cycle of a child component?
For example, if there is a parent component, Parent, and a child component, Child, and the parent component listens to the mounted child component, it will do some logical processing, which can be realized by the following way:
// <Child @mounted="doSomething"/> // mounted() { this.$emit("mounted"); } 1234567
Above, you need to manually trigger the parent component's event via $emit. A simpler way to do this is to listen to the parent component's reference to the child component via @hook, as shown below:
// <Child @hook:mounted="doSomething" ></Child> doSomething() { ('The parent component listens to the mounted hook function ...'); }, // mounted(){ ('Subcomponent trigger mounted hook function ...'); }, // The order of output above is: // Subcomponents trigger mounted hooks ... // The parent component listens to the mounted hook function ... 123456789101112131415
Of course, the @hook method doesn't just listen for mounted, it also listens for other lifecycle events such as created, updated, and so on.
12. What do you know about keep-alive?
keep-alive is a component built into Vue that allows included components to retain state and avoid re-rendering, with the following features:
Generally used in conjunction with routing and dynamic components for caching components;
The include and exclude attributes are provided, both of which support strings or regular expressions. include means that only components with matching names will be cached, and exclude means that any components with matching names will not be cached, with exclude having a higher priority than include;
There are two hook functions, activated and deactivated, which are triggered when the component is activated and deactivated when the component is removed.
13. Why is data a function in a component?
-
Why does data in a component have to be a function that then returns an object, whereas in a new Vue instance, data can just be an object?
Because components are used for reuse, and JS objects are referential, if data is an object in a component, then the scopes are not isolated, and the values of the data attribute in the subcomponents will affect each other.
If the data option in a component is a function, then each instance can maintain a separate copy of the returned object, and the values of the data attribute between component instances will not affect each other; instances of new Vue, on the other hand, are not reused, so there is no referencing of the object.
14. how does the v-model work?
In our vue project, we mainly use the v-model directive to create bi-directional data bindings on elements such as form input, textarea, select, etc. We know that v-models are essentially nothing more than syntactic sugar, where the v-model internally uses different attributes for different input elements and throws different events:
The text and textarea elements use the value attribute and the input event;
The checkbox and radio use the checked property and the change event;
The select field treats value as a prop and change as an event.
-
Take the input form element as an example:
<input v-model='something'> 1
equivalent to
<input v-bind:value="something" v-on:input="something = $"> 1
If in a custom component, the v-model will by default utilize a prop named value and an event named input, as shown below:
parent component: <ModelChild v-model="message"></ModelChild> subassembly: <div>{{value}}</div> props:{ value: String }, methods: { test1(){ this.$emit('input', 'Little Red') }, }, 1234567891011121314
15. What are the different ways to communicate between Vue components?
Vue inter-component communication is one of the knowledge points often tested in the interview, this question is a bit similar to the open question, you answer the more methods of course, the more points, indicating that you master Vue the more skillful.
Vue inter-component communication simply refers to the following three types of communication: parent-child component communication, intergenerational component communication, and sibling component communication. Below we introduce each type of communication and explain which type of inter-component communication this method can be applied to.(1) props / $emit Apply parent-child component communication
This approach is the foundation of Vue components, and I'm sure most of you are familiar with it, so I won't expand on it here.
(2) ref with $parent / $children applies Parent-child component communication
ref
: if used on a normal DOM element, the reference points to the DOM element; if used on a subcomponent, the reference points to the component instance
$parent / $children
: Access to parent/child instances(3) EventBus ($emit / $on) for parent-child, intergenerational, sibling component communication
This approach enables communication between any components, including parent-child, intergenerational, and sibling components, by using an empty Vue instance as a central event bus (event center) with which to trigger events and listen to them.
(4) $attrs/$listeners are suitable for intergenerational component communication.
$attrs
: Contains feature bindings (except class and style) from the parent scope that are not recognized (and fetched) by the prop. When a component does not declare any props, all parent-scope bindings (except class and style) are included here and can be accessed via thev-bind="$attrs"
Pass in internal components. Usually used in conjunction with the inheritAttrs option.
$listeners
: Contains the v-on event listener (without the .native modifier) in the parent scope. It can be accessed via thev-on="$listeners"
Passing in internal components(5) provide / inject applies to intergenerational component communication
Variables are provided in the ancestor component via provider and then injected in the descendant component via inject.
provide / inject API
It mainly solves the problem of communication between cross-level components, but its use scenario, mainly sub-components to obtain the state of the higher-level components, cross-level components to establish a kind of active provisioning and dependency injection relationship.(6) Vuex is suitable for parent-child, intergenerational, and sibling component communication.
Vuex is a state management model developed specifically for applications. At the heart of every Vuex application is a store. A "store" is basically a container that contains most of the state in your application.
The Vuex state store is responsive. When a Vue component reads state from the store, if the state in the store changes, the corresponding component will be efficiently updated accordingly.
The only way to change state in a store is to explicitly commit mutation, which makes it easy to keep track of every change in state.
16. Have you used Vue SSR? Tell us about SSR?
Vue is a framework for building client-side applications. By default, it is possible to export a Vue component to the browser for DOM generation and manipulation, however, it is also possible to render the same component as a server-side HTML string, send it directly to the browser, and finally "activate" the static markup into a fully interactive application on the client.
I.e.: SSR roughly means that vue in the client will be tag rendered into the entire html fragment of the work done on the server side, server-side formation of html fragments directly back to the client this process is called server-side rendering.
The advantages and disadvantages of server-side rendering of SSR are as follows:
(1) Advantages of server-side rendering:
Better SEO: because the content of the SPA page is obtained through Ajax, and search engine crawlers do not wait for the completion of Ajax asynchrony before crawling the page content, so the content of the page obtained through Ajax can not be crawled in SPA; while SSR is directly from the server to return to the page has been rendered (the data has been included in the page), so search engine crawlers can crawl the rendered page;
Faster content arrival time (faster loading of the first screen): SPA will wait for all Vue compiled js files to be downloaded before starting the page rendering, file downloads and so on require a certain amount of time, so the first screen rendering takes a certain amount of time; SSR is directly rendered by the server side of the page directly back to the display, no need to wait for the download of the js file and then go to the rendering, etc., so SSR has a much faster So SSR has a faster content arrival time;
(2) Disadvantages of server-side rendering:
More development constraints: for example, server-side rendering only supports the beforCreate and created hooks, which results in some external extensions needing to be handled specially in order to run in server-side rendering applications; and unlike SPA, which is a completely static single-page application that can be deployed on any static file server, a server-side rendering application needs to be running in the server environment;
More server load: Rendering a full application in is obviously more CPU-intensive than a server that just serves static files, so if you expect to use it in high traffic environments, prepare for the server load accordingly and use caching strategies wisely.
17. How many vue-router routing patterns are there?
vue-router has 3 routing patterns: hash, history, abstract, the corresponding source code is shown below:
switch (mode) { case 'history': = new HTML5History(this, ) break case 'hash': = new HashHistory(this, , ) break case 'abstract': = new AbstractHistory(this, ) break default: if (.NODE_ENV !== 'production') { assert(false, `invalid mode: ${mode}`) } } 123456789101112131415
The three routing patterns are described below:
hash: Use URL hash values for routing. Supports all browsers, including those that do not support the HTML5 History Api;
history : Depends on the HTML5 History API and server configuration. See the HTML5 History schema for details;
abstract : Supports all JavaScript runtime environments, e.g. server-side. If no browser API is found, the route will automatically force this mode.
18. Can you tell us how the hash and history routing patterns commonly used in vue-router are implemented?
(1) hash pattern implementation principle Early implementation of front-end routing is based on to realize. Its realization principle is very simple, the value is the content behind the # in the URL. For example, the following website, its value is '#search':
#search
The implementation of the hash routing model is based on the following characteristics:
The hash value in a URL is just a state on the client side, meaning that the hash part is not sent when a request is made to the server side;
Any change in the hash value adds a record to the browser's access history. We can therefore control the switching of hash values via the browser's back and forward buttons;
This can be done by using the a tag and setting the href attribute so that when the user clicks on the tag, the hash value of the URL is changed, or by using JavaScript to assign a value to the URL and change its hash value;
We can use the hashchange event to listen for changes in the hash value to jump (render) the page.
(2) History mode implementation principle HTML5 provides History API to realize the URL changes. The two main APIs are () and (). These two APIs can manipulate the browser's history without refreshing.The only difference is that the former adds a new history record, while the latter directly replaces the current one, as shown below:
(null, null, path);
(null, null, path);
The implementation of the history routing model is based on the existence of the following characteristics:
The pushState and repalceState APIs are used to implement URL changes;
We can use the popstate event to listen for url changes to jump (render) the page;
() or () will not trigger the popstate event, so we need to trigger the page jump (rendering) manually.
19. How does the Vue framework implement listening on objects and arrays?
Vue data bidirectional binding mainly means: data changes update the view, view changes update the data. That is:
When the content of the input box changes, the data in Data changes synchronously. That is, View => Data changes.
When the data in Data changes, the content of the text node changes synchronously. That is, Data => View changes.
Among them.View changes update the Data, which can be accomplished by event-listening.So Vue's bi-directional data binding works mostly as aHow to Update View Based on Data ChangesVue. Vue implements bi-directional data binding in the following 4 steps:
Implement a listener Observer: iterates over the data object, including the attributes of the sub-property object, and uses () to add setter and getter to the attributes, so that assigning a value to the object will trigger the setter, and then you can listen to the data change.
Implement a parser Compile: parses Vue template directives, replaces all variables in the template with data, then initializes the rendered page view and binds an update function to the node corresponding to each directive, adds a subscriber that listens to the data, and once the data has changed, receives a notification and calls the update function to update the data.
Implement a subscriber Watcher: The Watcher subscriber is a bridge between the Observer and the Compile. Its main task is to subscribe to messages about property value changes in the Observer, and when it receives a message about a property value change, it triggers the corresponding update function in the Compile of the parser.
Implement a subscriber Dep: The subscriber uses the publish-subscribe design pattern to collect subscriber Watchers and manage the listener Observer and subscriber Watcher in a unified way.
20. How does Vue implement bi-directional data binding?
If you are asked how Vue implements two-way data binding, you will surely answer that it hijacks the data through (), but () can only hijack data from properties, not from the whole object. Similarly, you can't hijack an array, but as we know from using the Vue framework, Vue can detect changes to objects and arrays (some of the methods), so how does it do it? Let's look at the code below:
/** * Observe a list of Array items. */ observeArray (items: Array<any>) { for (let i = 0, l = ; i < l; i++) { observe(items[i]) // observe function for monitoring changes in data } } /** * Recursive traversal of attributes */ let childOb = !shallow && observe(val) // observe function for monitoring changes in data 12345678910111213
By looking at the Vue source code above, we can see that the Vue framework uses () to listen to objects and arrays (and some methods) by traversing arrays and recursively traversing objects.
21. How does Vue use vm.$set() to solve the problem of unresponsive object additions?
Due to the limitations of modern JavaScript, Vue cannot detect the addition or removal of object properties. Since Vue performs getter/setter transformations on properties when initializing an instance, a property must exist on the data object in order for Vue to convert it to responsive. However, Vue provides the
(object, propertyName, value) / vm.$set (object, propertyName, value)
to implement adding responsive properties to objects, so how does the framework itself do it?
Let's look at the corresponding Vue source code:
vue/src/core/instance/
export function set (target: Array<any> | Object, key: any, val: any): any { // target is an array if ((target) && isValidArrayIndex(key)) { // Modify the length of the array to avoid index>array length causing splcie() to execute incorrectly. = (, key) // Trigger responsive using the array's splice mutation method (key, 1, val) return val } // The key already exists, modify the value directly if (key in target && !(key in )) { target[key] = val return val } const ob = (target: any).__ob__ // The target itself is not responsive data, so assign it directly. if (!ob) { target[key] = val return val } // Responsive processing of attributes defineReactive(, key, val) () return val } 12345678910111213141516171819202122232425
As we can see from reading the source code above, vm.$set is implemented as:
If the target is an array, use the splice method of the array to trigger the corresponding equation;
If the target is an object, it will first read whether the property exists and whether the object is responsive, and ultimately, if the property is to be processed responsively, it will be processed responsively by calling the defineReactive method (the defineReactive method is the method called by Vue to dynamically add a getter and a setter to the object's properties when the object is initialized). method that Vue calls when initializing an object to dynamically add getters and setters to its properties)
22. What are the advantages and disadvantages of virtual DOM?
Pros:
Guaranteed performance floor: The framework's virtual DOM needs to be adapted to any operations that may be generated by the upper-level API, and its implementation of some DOM operations must be pervasive, so its performance is not optimal; however, it is much better than brute-force DOM operations, so the framework's virtual DOM is guaranteed to provide at least decent performance when you don't need to manually optimize it, which means that it is not optimal. guaranteed lower bound on performance;
No need to manually manipulate the DOM: We no longer need to manually manipulate the DOM, we just need to write the View-Model code logic, the framework will be based on the virtual DOM and data bi-directional binding, to help us to update the view in a predictable way, which greatly improves our development efficiency;
Cross-platform: Virtual DOMs are essentially JavaScript objects, whereas DOMs are strongly platform-dependent. In contrast, virtual DOMs allow for easier cross-platform operations, such as server rendering, weex development, and so on.
Disadvantages.
Inability to perform extreme optimization: While virtual DOM + reasonable optimization is sufficient to meet the performance needs of most applications, virtual DOM is not able to perform targeted extreme optimization in some applications with very high performance requirements.
23. How is the virtual DOM implemented?
The principle of virtual DOM implementation consists of the following 3 parts:
Simulate the real DOM tree with JavaScript objects to abstract the real DOM;
diff algorithm - compares the differences between two virtual DOM trees;
pach algorithm - applies the difference between two virtual DOM objects to the real DOM tree.
24. What does a key do in Vue?
The key is a unique token for the vnode in Vue, and with this key, our diff operations can be more accurate and faster. Vue's diff process can be summarized as follows: oldCh and newCh each have two head and tail variables oldStartIndex, oldEndIndex and newStartIndex, newEndIndex, they will be the new node and the old node will be compared two by two, that is, there are a total of four ways to compare: newStartIndex and oldStartIndex, newEndIndex and oldEndIndex, newStartIndex and oldEndIndex, newEndIndex and oldStartIndex. and oldStartIndex, newEndIndex and oldEndIndex, newStartIndex and oldEndIndex, newEndIndex and oldStartIndex, if the above four comparisons do not match, if the key is set, the key will be used to compare again, in the process of comparison. In the process of comparison, the traversal will be in the middle, once StartIdx > EndIdx indicates that at least one of the oldCh and newCh has been traversed, the comparison will end.So the role of the key in Vue is that the key is a unique token for the vnode in Vue, and by using this key, our diff operations can be more accurate and faster!
More accurate: because with a key it's not in-place reuse, and in the sameNode function === comparison it avoids in-place reuse. So it will be more accurate.
Faster: Use the uniqueness of the key to generate a map object to get the corresponding node, which is faster than traversing, the source code is as follows:
function createKeyToOldIdx (children, beginIdx, endIdx) { let i, key const map = {} for (i = beginIdx; i <= endIdx; ++i) { key = children[i].key if (isDef(key)) map[key] = i } return map } 123456789
25. What optimizations have you made to the Vue project?
(1) Code-level optimization
Distinguish between v-if and v-show.
computed and watch distinguish between usage scenarios
v-for traversal must add a key to the item and avoid using v-if at the same time.
Long list performance optimization
Destruction of events
Lazy loading of image resources
lazy loading of routes
On-demand introduction of third-party plug-ins
Optimize infinite list performance
Server-side rendering SSR or pre-rendering
(2)Webpack Optimization at the level of
Webpack Compressing Images
Reducing Redundant Code for ES6 to ES5 Conversions
Extract public code
Template pre-compilation
Extracting the CSS of a component
Optimize SourceMap
Analysis of the output of the build results
Compile Optimization for Vue Projects
(3) Optimization of basic Web technologies
Enable gzip compression
browser cache
CDN Usage
Finding performance bottlenecks with Chrome Performance
26. What do you know about vue3.0 features?
The goal of Vue 3.0 is to make the Vue core smaller, faster, and more powerful, so Vue 3.0 adds these new features:
(1) Changes to the monitoring mechanism 3.0 will bring a proxy-based observer implementation that provides full language coverage for reactive tracking. This removes many of the limitations of Vue 2's proxy-based implementation:
Only properties can be monitored, not objects
Detects the addition and removal of attributes;
Detects changes in array index and length;
Supports Map, Set, WeakMap and WeakSet.
The new observer also provides the following features:
This provides a simple and lightweight solution for cross-component state management in small- to medium-scale scenarios.
Inert observations are used by default. In , reactive data is observed at startup regardless of how large it is. If your dataset is large, this may introduce significant overhead at application startup. In , only the data used to render the initially visible part of the application is observed.
More precise notification of changes. In , forcing a new property to be added will cause watchers that depend on that object to be notified of the change. In , only watchers that depend on a specific property will be notified.
Immutable observable: We can create "immutable" versions of values (even nested properties) unless the system temporarily "unblocks" them internally. This mechanism can be used to freeze prop passes or changes outside of the Vuex state tree.
Better debugging: We can use the new renderTracked and renderTriggered hooks to track exactly when and why a component is re-rendering.
(2) Templates There are no major changes to the templates, only the scope slots, the mechanism that causes the parent component to re-render when the scope slots change, and 3.0 changes the scope slots to functions, which only affects the re-rendering of the child component and improves rendering performance. At the same time, vue 3.0 will also make a series of changes to the render function aspect to make it easier to get used to using the api to generate vdom directly.
(3) Object-based component declaration The components in 3.0 are declared by passing a series of options, and the combination with TypeScript needs to be done through some decorators, which can realize the function, but it's quite troublesome. In 3.0, we changed the way components are declared to a class style, which makes it easy to integrate with TypeScript. In addition, the source code of vue is also written in TypeScript. In fact, when the functionality of the code is complex, there must be a static type system to do some auxiliary management. Now vue3.0 has been rewritten in TypeScript, which makes it easier to combine TypeScript with the externally exposed api, and a static type system is really necessary for the maintenance of complex code.
(4) Other changes The changes in vue3.0 are comprehensive, and the above only covers the main 3 areas, there are some other changes:
Support for custom renderers allows weex to be extended by customizing the renderer, rather than directly forking the source code to change it.
Support for Fragment (multiple root nodes) and Protal (rendering of the formation content in the rest of the dom) components is handled for some special scenarios.
Based on treeshaking optimization, it provides more built-in functions.
27. Responsive principles (change detection)
Combining data hijacking and template compilation using the publish-subscribe pattern for two-way binding
1. observer: The encapsulation method is used to hijack the getter and setter of an object's properties as a way to track data changes.
2、Read data trigger getter to collect dependency(Watcher) to Dep. 3、Modify data trigger setter and traverse the dependency list to notify all related dependency(Watcher) 4、Dep class find a place to store dependency for dependency, used to collect and manage dependency, collect in getter, notify in setter. 5, Watcher class is the collected dependencies, actually a subscriber, Watcher will assign its own instance to the (global variable) on, and then go to actively access the property, triggering the getter of the property, the getter will collect this Watcher into Dep, Watcher's update method will be called in Dep's notification method The update method of Watcher will be called in the notification method of Dep. 6, Observer class is used to make all the attributes and sub-attributes of an object responsive, which is realized by recursively calling defineReactive. 7. $set and $delete APIs are provided because it is not possible to detect the addition/deletion of attributes on an object5 .
28. How does it work, the three parameters? What do they do?
() method will either define a new property directly on an object or modify an existing property of an object and return this object.
obj:Objects that require attributes to be defined prop:Attributes to be defined {}:Attribute descriptors to be defined or modified。 value: "18", // set defaults (mutually exclusive with get()) enumerable: true, //This sentence controls the attributes that can be enumerated enumerable Change it to true to participate in traversal Default value false writable: true, // Whether the property is writable Default value false (mutually exclusive with set()) configurable: true, // Whether this property can be deleted Default value false get // The get function is called when someone reads the prop, and returns the value of sss. set // The set function is called when someone modifies the prop, and takes one argument, which is the modified value. 123456789
29. What is the difference between the responsive principles of both vue2 and vue3?
vue2 uses it, but vue3 uses Proxy.
Drawbacks:
-
You can only listen on one property at a time, you need to iterate to listen on all properties.
-
For new properties of an object, you need to manually listen to the
-
For arrays passing
push
、unshift
method, nor can it listen for elements added by the
Proxy doesn't have this problem and can listen to the whole object for data changes, so with vue 3.0 will use Proxy instead of definedProperty.
30. Vue's patch diff algorithm
Instead of redrawing the entire view based on the new VNode, patch compares the old and new VNode nodes and then modifies the view by the smallest unit based on the result of the comparison between the two. patch's core lies in the diff algorithm, which efficiently compares the changes in the virtual DOM and derives the changes to modify the view.
The core of the diff algorithm is to compare the tree nodes in the same layer instead of traversing the tree in a layer-by-layer search, so the time complexity is only O(n), which is a fairly efficient algorithm.
-
Same-level comparisons (compare only the same level, not across levels)
-
If the tags are not the same, they will be deleted and rebuilt without in-depth comparison.
-
tag and key, both of which are the same, are considered to be the same node and will be compared in depth
31. Vue template compilation principles
-
Template string Convert toelement AST (parser)
Vue-loader cuts and parses .vue files (parseHTML cuts by tag on outgoing and incoming stacks (self-closures are handled directly without stacks), maintains parent-child relationships on outgoing stacks) to generate ASTs (Abstract Syntax Trees)
using a large number of regular matches for the start and end tags, while the pointer locates the parse position, the
-
Static node tagging of ASTs, mainly used for virtual DOM rendering optimization (optimizer)
No diff static nodes on dom updates.
-
Using element AST to generate render function code strings (code generator)
Vue-template-compiler then parses it into render (executable function string-with(this)=>{return _c('div')}), new Function generates the function, which is passed to the component's render
Calling render directly when rendering a component is sufficient.
32. Summary of Vue principles
[Template Compilation] Template template, after compiling the system to generate VNode, (template string → AST → Render function)
[Rendering] and then the rendering system to generate the VNode into the real DOM (&& Mount mounts to the real DOM node)
[Responsive] Listening to data through a responsive system that triggers dependencies (components) when the data changes
[Diff & Patch] After receiving the notification within the component, it will compare the changes of VNode through diff algorithm to reuse the code as much as possible to find out the smallest difference and ensure the minimum performance consumption.
After getting the VNode that needs to be added/deleted/modified, go to operate the real DOM one by one to modify it (select the corresponding real DOM node through the selector to modify it).
Webpack Part VI
1. talk about your understanding of Webpack (what is Webpack?)
Webpack is a static module packer that analyzes the dependencies of modules. All resources in a project are modules, and by analyzing the dependencies between modules, it recursively builds a dependency graph inside of them that contains every module needed by the application, and then packs these modules into one or morebundle
The final output module is HTML, JavaScript, CSS and static files (images, fonts, etc.). The final compiled output modules are HTML, JavaScript, CSS and various static files (images, fonts, etc.).
webpack is like a production line, after a series of processing processes (loader) in order to convert the source file into the output. The production line of each process is a single responsibility, there are dependencies between multiple processes, only after the completion of the current process can be handed over to the next process to deal with. Plugin is like a function inserted into the production line, at a specific time on the production line of resources to do processing. webpack in the running process will broadcast events , plug-ins only need to listen to the events it cares about , you can join the production line , to change the operation of the production line .
The main role of webpack is as follows:
-
Module Packaging It is possible to package different modules together and ensure that they are referenced correctly and executed in an orderly manner. Using packaging we can freely divide the files into modules according to our own business during development to ensure the clarity and readability of the project structure.
-
Compilation compatibility In the front-end "ancient times", hand-written a bunch of browser-compatible code has been a front-end engineers scalp numb things, but today this problem has been greatly weakened by webpack's Loader mechanism can not only help us do polyfill code, but also can compile and convert files such as . Convert files such as .less, .vue, .jsx, which can not be recognized in the browser format, so that we can use the new features and new syntax to do development, improve development efficiency.
-
Capability Extension Through webpack's Plugin mechanism, we can achieve modular packaging and compilation compatibility based on the further implementation of features such as on-demand loading, code compression and a series of features to help us further improve the degree of automation, engineering efficiency and the quality of the output of the package.
2. Webpack packaging process/packaging principle/build flow?
-
Initialization: start the build, read and merge configuration parameters, load the plugin, instantiate the Compiler.
-
Compile: Starting from Entry, for each Module, serially call the corresponding Loader to translate the contents of the file, and then find the Module that the Module depends on, and recursively compile the process.
-
Output: Combine compiled Modules into Chunk, convert Chunk to file, output to file system.
The details:
Webpack CLI The yargs module parses the CLI parameters and transforms them into a configuration object option (single-entry: Object, multi-entry: Array), which calls webpack(option) to create the compiler object.
If so, iteratively call() to register the plugin.
Determines if watch is turned on, if so calls , otherwise calls , and starts building.
Create a Compilation object to collect all the resources and information, and then trigger the make hook.
The make phase recurses all dependencies from the entry point.
Each traversal calls the corresponding Loader to translate the contents of the file, and then generates an AST, which is traversed to find the next dependency to continue the recursion.
Assembles chunks based on relationships between entries and modules and outputs them into a file in dist.
During the above process, webpack will be used at a specific point in time (using thetapable module) to broadcast specific events, the plugin listens to the events and executes the corresponding logic, and the plugin can call the api provided by webpack to change the results of webpack's operation
3. Role of the loader
In webpack, theloader is a functionThe main purpose is toImplementation of source code conversionso the loader function willtake a source code as a parameter, for example, convert ES6 to ES5, convert less to css, and then convert css to js to be able toEmbedded in html file。
By default, webpack only supports packaging js and json files, but other types of files such as css, html, png, webpack can not help. Therefore, you need to configure the corresponding loader for file content analysis and conversion.
4. What are some common Loaders and what problems do they solve?
The commonly used loaders are as follows:
-
image-loader: load and compress image files.
-
less-loader: load and compile LESS files.
-
sass-loader: load and compile SASS/SCSS files.
-
css-loader: load CSS, support modularity, compression, file import and other features, the use of css-loader must be used in conjunction with the use of style-loader.
-
style-loader: Used to mount the CSS compiled style to the style tag of the page. You need to pay attention to the loader execution order, style-loader should be put in the first place, loader is executed from back to front.
-
babel-loader: converting ES6 to ES5
-
postcss-loader: extends CSS syntax to use next generation CSS, can be used with autoprefixer plugin to auto-complete CSS3 prefixes.
-
eslint-loader: Check JavaScript code with ESLint.
-
vue-loader: loads and compiles Vue components.
-
file-loader: outputs files to a folder, references the output file in code via a relative URL (handles images and fonts)
-
url-loader: similar to file-loader, the difference is that user can set a threshold, greater than the threshold will be handed over to the file-loader to process, less than the threshold to return to the file base64 form of the encoding (processing images and fonts).
-
source-map-loader: load additional Source Map files for breakpoint debugging.
5. Role of plugins
A plugin is a classThe class has aThe apply() method, which is primarily used by thePlugin installation, in which you can listen to some events emitted from the compiler and do something at the right time.
Plugins in webpack give it all kinds of flexibility, such as packaging optimization, resource management, environment variable injection, etc. They run in different phases (hooks/lifecycles) of webpack, throughout the entire webpack build cycle. The goal is to "solve the other things that the loader can't do".
6. What are some common Plugins and what problems do they solve?
-
html-webpack-plugin: allows you to copy a structured html file and automatically bring in all the resources (JS/CSS) of the packaged output
-
clean-webpack-plugin: Automatically empties the dist directory when repacking.
-
mini-css-extract-plugin: extracts css from js into a single file.
-
optimize-css-assets-webpack-plugin: compressing css
-
uglifyjs-webpack-plugin: compressing js
-
commons-chunk-plugin: extract public code
-
define-plugin: define environment variables
7. Difference between Loader and Plugin in Webpack
timing of operation Runs in compilation phase Works throughout the cycle
Usage Loader:1.download 2.use Plugin:1.download 2.reference 3.use
loader is a file loader, can load resource files, and these files for some processing, such as compilation, compression, etc., and ultimately packaged together into the specified file; plugin gives webpack a variety of flexible features, such as packaging optimization, resource management, environment variable injection, etc., the purpose is to solve the loader can not be achieved by other things.
In terms of timing, the loader runs before the packaged file; the plugin works throughout the entire compilation cycle.
In terms of configuration, loader is configured in as the module's parsing rules and is of type array. Each item is an Object, containing properties such as test (type file), loader, options (parameters), etc.; plugin is configured separately in plugins, with type as an array, and each item is an instance of a plugin, with parameters passed in through the constructor.
8. How does webpack's hot update work? Explain its principle?
The core of a hot update is that the client pulls the updated file from the server, chunk diff to be precise (the part of the chunk that needs to be updated). In fact, a websocket is maintained between the webpack-dev-server and the browser, and when the local resource changes, the webpack-dev-server will pushes an update to the browser with a build-time hash for the client to compare to the last resource. The client compares the differences and then makes an Ajax request to the webpack-dev-server to retrieve the changes (file list, hash) so that the client can then use this information to continue to make jsonp requests to the webpack-dev-server to retrieve incremental updates to the chunk.
The follow-up part (what to do with the incremental updates after you get them? Which states should be kept? What needs to be updated?) is done by the HotModulePlugin, which provides APIs for developers to handle their own scenarios, like thereact-hot-loader and vue-loader both implement hot updates with the help of these APIs.
Detailed: 1, in the watch mode of webpack, a file in the file system has been modified, webpack listens to the file changes, according to the configuration file on the module to recompile and packaged, and will be packaged code through a simple JavaScript object to save in memory. 2. Interface interaction between webpack-dev-server and webpack, and in this step, it is mainly the interaction between the middleware of dev-server, webpack-dev-middleware, and webpack. webpack-dev-middleware calls webpack's exposed API exposed by webpack to monitor code changes and tell webpack to package the code into memory. 3. webpack-dev-server monitors file changes. Unlike the first step, this step does not monitor code changes for repackaging. When we configure the configuration file to be true, the Server listens for changes to the static files in the configuration folder, and then notifies the browser to perform a live reload of the application after the changes have been made. note that this is a browser refresh, which is not the same concept as HMR. 4. webpack-dev-server code work, the step is mainly done through the The main purpose of this step is to establish a long websocket connection between the browser and the server via sockjs (a dependency of webpack-dev-server), which informs the browser of the state of each stage of webpack compilation and packaging, as well as the Server listening for changes in static files in the third step. The browser then uses these socket messages to do different things. Of course, the main piece of information passed to the server is the hash value of the new module, which is used in later steps to hot swap the module. The webpack-dev-server/client doesn't ask for newer code and doesn't perform hot-replacements, but rather passes that work back to webpack, and webpack/hot/dev-server does its job based on the information passed to it by webpack-dev-server/client and the configuration of the dev-server. and the dev-server's configuration to decide whether to refresh the browser or do a hot update of the module. Of course, if it just refreshed the browser, it wouldn't have to do any of those steps. It is the hub of the client's HMR. It receives the hash value of the new module passed to it in the previous step, and sends an Ajax request to the server, which returns a json containing the hash values of all the modules to be updated, and after getting the list of updates, the module makes another jsonp request to get the latest module code. 5, the key step to decide whether HMR is successful or not, in this step, HotModulePlugin will compare the old and new modules, decide whether to update the module or not, after deciding to update the module, check the dependency relationship between the modules, update the module at the same time update the dependency references between the modules. In the last step, when HMR fails, it will fall back to live reload operation, that is, it will refresh the browser to get the latest packaged code.
9. How to resolve circular dependencies
Webpack replaces require withwebpack_requireIf it has been loaded, it will return the previous export directly and will not reload it again.
10. How to increase the speed of Webpack builds
1. Code compression
JS Compression webpack 4.0 supports code compression by default in production environments, i.e. in mode=production. In fact, webpack 4.0 uses the terser-webpack-plugin compression plugin by default, and before that it used uglifyjs-webpack-plugin, the difference between the two is that the latter is not very good at compression for ES6, and we can turn on the parallel parameter to use multi-process compression to speed up compression.
CSS Compression CSS compression is usually about removing useless spaces, etc., as it is difficult to modify selectors, property names, values, etc. Another plugin can be used: css-minimizer-webpack-plugin.
HTML compression When using the HtmlWebpackPlugin plugin to generate HTML templates, configure the attribute minify for html optimization.
= { plugin:[ new HtmlwebpackPlugin({ minify:{ minifyCSS: false, // Whether to compress css collapseWhitespace: false, // Whether to collapse spaces removeComments: true // Whether to remove comments } }) ] } 1234567891011
2. Image compression
configure
image-webpack-loader
3. Tree Shaking
Tree shaking is a term used in computing to denote the elimination of dead code, relying on static syntax analysis of ES Modules (without executing any code, module dependencies can be known explicitly). There are two options for implementing Tree shaking in webpack:
usedExports: Optimized by marking whether certain functions are used or not, and then optimized by Terser.
= { ... optimization:{ usedExports } } 123456
After use, the unused code will be added to the webpack package with the unused harmony export mul comment, which is used to inform Terser that the code can be removed during optimization.
sideEffects: skip the whole module/file and see if the file has side effects directly
sideEffects is used to tell webpack compiler which modules have side effects, the way to configure this is to set the sideEffects attribute in. If sideEffects is set to false, it tells webpack that it is safe to remove unused exports. if some files need to be kept, you can set them as an array, for example:
"sideEffecis":[ "./src/util/", "*.css" // all css files ] 1234
4. Reduction of the packing area
Exclude modules that webpack does not need to parse, i.e., go in as few modules as possible when using the loader. You can specify which modules the loader will be applied to and which modules it will not be applied to with the help of the include and exclude parameters.
5. Reducing redundant code for ES6 to ES5 conversion
utilizationbable-plugin-transform-runtime
plug-in (software component)
6. Extraction of public codes
Pump out public code from multiple pages into separate files by configuring the CommonsChunkPlugin plugin
7. Other
Component lazy loading, route lazy loading, turn on gzip, public third-party packages on cdn, configure cache to cache Loader's compiled copies of files, configure resolve to increase the speed of file search (@: src)
VII. Performance Optimization
1. Browser cache optimization
in order forbrowser cache
To make the most of it, the strategy tries to work by following these five pointsbrowser cache
Maximum Role.
-
"Consider denying all caching policies.":
Cache-Control:no-store
-
"Consider whether the resource is requested from the server every time":
Cache-Control:no-cache
-
"Consider whether a resource is cached by a proxy server".:
Cache-Control:public/private
-
"Consider resource expiration time":
Expires:t/Cache-Control:max-age=t,s-maxage=t
-
"Consider Negotiating a Cache":
Last-Modified/Etag
caching strategy
By setting theHTTP
The message implementations, which are formally divided into"Strong Cache/Forced Cachecap (a poem)"Negotiation Cache/Comparison Cache. In order to facilitate the comparison, the author will show certain details using illustrations, I believe you have a better understanding.
totalcaching strategy
The mechanism is clear.Go to the strong cache first, and negotiate the cache only if the hit fails
The If the hitstrong cache
The direct use of thestrong cache
If not hit.strong cache
If you have a hit, send a request to the server to check for a hit.negotiation cache
if it hitsnegotiation cache
The server returns a 304 to notify the browser of the use of thelocal cache
Otherwise, returnLatest resources
。
There are two more common application scenarios worth usingcaching strategy
A try, of course more application scenarios can be developed according to the project needs.
-
"Frequent changes in resources": Settings
Cache-Control:no-cache
to make the browser send a request to the server every time, in conjunction with theLast-Modified/ETag
Verify that the resource is valid -
"fluctuating resources": Settings
Cache-Control:max-age=31536000
The new file name is generated when the code is modified, and the latest file is downloaded only when the file name is changed in the HTML file.
2. Render-level performance optimization
"Rendering Level"of performance optimization is undoubtedly how to make codeBetter parsing for faster execution
The author has made recommendations in the following five areas. The author therefore makes recommendations in the following five areas.
-
"CSS Strategy: Based on CSS rules
-
"DOM Strategy": DOM-based operations
-
"Blocking strategy.": Script-based loading
-
"Returning to Redraw Strategy.": Based on reflow repainting
-
"Asynchronous Update Policy": Based on asynchronous updates
The above five aspects are all accomplished when writing code, and are filled in the development phase of the entire project process. Therefore, it is important to pay attention to each of the following points during the development phase and to develop good development habits.performance optimization
It is also naturally being used.
rendering level
(used form a nominal expression)performance optimization
It shows up more in the coding details than in the physical code. It simply means that certain coding rules are followed in order to put therendering level
(used form a nominal expression)performance optimization
Make the most of it.
"Returning to Redraw Strategy."existrendering level
(used form a nominal expression)performance optimization
It is the most important and conventional of theperformance optimization
One of them. The nuggets booklet "Playing with the Artistic Beauty of CSS" released by the author last year uses a whole chapter to explainrepaint
, this chapter is up for beta reading, for more details poke here.
CSS Strategy
-
Avoid more than three layers of
nested rule
-
avoiding the need for
ID Selector
Adding redundant selectors -
Avoid using
tag selector
substitute (X for Y, or a number in an algebraic expression)class selector
-
Avoid using
wildcard selector
The rule is declared only for the target node -
Avoid duplicate matches duplicate definitions, focus on
Inheritable properties
DOM Policy
-
(computing) cache
DOM Calculated Properties
-
Avoid too much
DOM operations
-
utilization
DOMFragment
Cache BatchingDOM operations
obstructionist strategy
-
Scripts and
DOM/other scripts
The dependencies are strong: the dependency on<script>
set updefer
-
Scripts and
DOM/other scripts
The dependencies are not strong: the dependencies on<script>
set upasync
Reflow redrawing strategy
-
(computing) cache
DOM Calculated Properties
-
Use class merge styles to avoid changing styles line by line
-
utilization
display
containmentdom dom (computing)
willDOM Offline
Asynchronous update strategy
-
exist
asynchronous task
modificationsDOM
When packaging it as amicrotask
3. Six indicators of performance optimization
Six indicators
Most of them.performance optimization
Details that can be used asThe Nine Strategies
of the supplement. The author bases each articlePerformance Optimization Recommendations
The characterization willnorm
It is divided into the following six areas.
-
"Load Optimization: Performance optimizations that can be made when resources are loaded
-
"Execution Optimization": Performance optimizations that can be made by resources at execution time
-
"Render Optimization": Performance optimizations that can be made when resources are rendered
-
"Style Optimization: Styles can be optimized for performance at coding time
-
"Script Optimization: Performance optimizations that can be made when scripts are coded
-
"V8 Engine Optimization": In response to
V8 engine
Performance optimizations that can be made for features
VIII. Other miscellaneous
1. What are the common browser kernels?
Mainly divided into two parts: rendering engine (layout engineer or Rendering Engine) and JS engine.
Rendering engine: It is responsible for obtaining the content of the web page (HTML, XML, images, etc.), organizing the information (e.g., adding CSS, etc.), and calculating how the web page is to be displayed, and then outputting it to a monitor or printer. Browser kernels interpret the syntax of a web page differently, and therefore render it differently. The kernel is required by all web browsers, e-mail clients, and other applications that need to edit and display web content.
JS engine: parsing and execution of javascript to achieve dynamic effects of the web page.
In the beginning the rendering engine and the JS engine were not clearly distinguished, then the JS engine became more and more independent and the kernel tended to refer only to the rendering engine.
Common Kernels
Trident kernel: IE, MaxThon, TT, The World, 360, Sogou Browser, and more. [aka MSHTML]
Gecko kernel: Netscape 6 and above, FF, MozillaSuite / SeaMonkey, etc.
Presto kernel: Opera7 and above. Opera kernel: Opera7 and above. [Opera kernel was: Presto, now: Blink;]
Webkit kernels: Safari, Chrome, etc. [Chrome: Blink (a branch of WebKit)]
2. What are some ways to optimize the performance of a web front-end?
1. compress css, js, images 2. reduce the number of http requests, merge css, js, merge images (Sprite) 3. use CDN 4. reduce the number of dom elements 5. lazy loading of images 6. static resources in addition to the use of non-cookie domain name 7. reduce the access to the dom (cached dom) 8. cleverly delegate the use of events 9. stylesheets on the top, the scripts placed in the low
3. What is the process that a web page undergoes from the entry of the URL to its rendering?
It can be roughly divided into 7 steps as follows:
Enter the URL;
Send it to a DNS server and get the ip address of the web server corresponding to the domain name;
Establish a TCP connection with the web server;
The browser sends an http request to the web server;
The web server responds to the request and returns data for the specified url (or an error message, or a new url address for redirection);
The browser downloads the data returned by the web server and parses the html source file;
Generate DOM tree, parse css and js, render page until display is complete;
4. What is the difference between a thread and a process?
A program has at least one process, and a process has at least one thread.
Threads are divided on a smaller scale than processes, making multithreaded programs highly concurrent.
In addition, processes have separate memory units during execution, while multiple threads share memory, thus greatly improving the efficiency of program operation.
Threads are still distinct from processes in their execution. Each independent thread has an entry point for program execution, a sequential execution sequence, and an exit from the program. However, threads cannot execute independently and must be dependent on the application program, which provides multiple thread execution controls.
From a logical point of view, the significance of multiple threads is that there are multiple executing parts of an application that can be executed simultaneously. However, the operating system does not view multiple threads as multiple independent applications for process scheduling and management and resource allocation. This is the important difference between processes and threads.
5. What are common HTTP status codes?
100 Continue Continue, generally in sending post request, has sent the http header after the server will return this information, that is, to confirm, and then send the specific parameters of the information 200 OK Normal return information 201 Created The request was successful and the server created a new resource 202 Accepted The server has accepted the request, but has not yet been processed 301 Moved Permanently The requested page has been permanently moved to a new location. 302 Found Temporary redirection. 303 See Other Temporary redirection and always uses GET to request a new URI. 304 Not Modified The requested page has not been modified since the last request. 400 BadRequest The server could not understand the format of the request and the client should not attempt to initiate the request again with the same content. 401 Unauthorized The request is unauthorized. 403 Forbidden Access is forbidden. 404 Not Found Could not find how to match the URI to the resource. 500 Internal Server Error The most common server-side error. 503 Service Unavailable The server side is temporarily unable to process the request (possibly due to overload or maintenance).
6. Lazy loading of images?
triggered when the page is scrolled -> loads the image -> determines if the image is in the visible area -> if it is, dynamically assigns the value of data-src to the image
7. Mobile performance optimization?
Use css3 animation as much as possible, turn on hardware acceleration
Appropriate use of touch time instead of click time
Avoid css3 gradient shadow effects
Hardware acceleration can be enabled with transform: translateZ(0)
Do not abuse float. float is more computationally intensive when rendering, minimize the use of the
No abuse of web fonts. web fonts need to be downloaded, parsed, and redrawn on the current page.
Proper use of requestAnimationFrame animation instead of setTimeout
Properties in css (css3 transitions, css3 3D transforms, opacity, webGL, video) trigger GUP rendering, which consumes power
8. Three handshake, four wave strategy for TCP transport
Three handshakes:
In order to accurately send data to the target, the TCP protocol uses three handshake strategy. After the packet is sent out using the TCP protocol, TCP will not ignore the situation after transmission, he will certainly confirm to the other party whether the delivery, the handshake process using the TCP flags: SYN and ACK
The sender first sends a packet with the SYN flag to the other side.
Upon receipt, the receiving end sends back a packet with the SYN/ACK flag to convey an acknowledgement message
Finally, the sender sends back a packet with the ACK flag, representing the end of the handshake.
If there is an inexplicable interruption at some point during the handshake, the TCP protocol sends the same packets again in the same order
It takes "four waves" to disconnect a TCP connection.
First wave: the active shutdown party sends a FIN to focus on the data transfer from the active party to the passive shutdown party, i.e., the active shutdown party warns the passive shutdown party: I'm not going to send you any more data (data sent before the FIN packet will still be re-sent by the active shutdown party if it does not receive the corresponding ACK acknowledgement message). However, at this point, the active shutdown party can still accept the data
Second wave: the passive shutdown party receives the FIN packet and sends an ACK to the other party, acknowledging the serial number received serial number +1 (same as SYN, one FIN occupies one serial number)
Third wave: the passive shutdown party sends a FIN to close the data transfer from the passive shutdown party to the active shutdown party, i.e., to tell the active shutdown party, "I'm done sending data, I won't be sending you any more data".
Fourth wave: the active shutdown party receives the FIN, sends an ACK to the passive shutdown party, and the acknowledgement serial number is the received serial number + 1, so that the four waves are completed
9. HTTP and HTTPS, why is HTTPS secure?
HTTP protocol is usually carried on top of the TCP protocol, add a security protocol layer (SSL or TSL) between HTTP and TCP, at this time, it is often referred to as HTTPS
The default port number is 80 for HTTP and 443 for HTTPS
Because the network request needs to be in the middle of a lot of servers routing forwarding, the middle of the nodes may tamper with the information, and if you use HTTPS, the key is only in you and the end station, https all that is safer than http, because he utilizes the ssl/tls protocol transmission. Contains certificates, traffic forwarding, load balancing, page adaptation, browser adaptation, refer pass, etc., to protect the security of the transmission process
10. Comparison of the differences between axios and fetch
axios is a Promise-based HTTP client for browsers and nodejs, and is essentially a wrapper around native XHR, except that it is an implementation of Promise that conforms to the latest ES specification, which itself has the following features
-
Creating an XMLHttpRequest from a Browser
-
Promise API support
-
Client-side support to prevent CSRF
-
Provides some interfaces for concurrent requests (important, facilitates a lot of operations)
-
Creating http requests from
-
Intercepting requests and responses
-
Converting request and response data
-
Cancel request
-
Automatic conversion of JSON data
fetch advantage:
-
Syntax is concise and more semantic
-
Based on standard Promise implementation, supports async/await.
-
Isomorphic convenience, using isomorphic-fetch
-
More low-level, rich API provided (request, response)
-
Off the XHR, it's a new implementation in the ES specification
Problems with fetch
-
fetch is a low-level API that you can think of as native XHR, so it's not that comfortable to use and needs to be wrapped.
-
fetch only reports errors on network requests, 400, 500 are treated as successful requests, the server does not reject when it returns 400, 500 error codes, only network errors that cause the request to be incomplete, fetch will be rejected.
-
fetch will not take cookies by default, you need to add a configuration item: fetch(url, {credentials: 'include'})
-
fetch does not support abort, does not support timeout control, the use of setTimeout and the implementation of the timeout control does not prevent the request process to continue to run in the background, resulting in a waste of traffic
-
fetch has no way to natively monitor the progress of a request, whereas XHR can
IX. Subjective Part
1. What projects have you worked on? Talk specifically about the techniques used in a particular project.
Note: Find the project you feel most comfortable with (the most complex, most technical project), and add some technical terms to the description as much as possible Layout We use html5+css3 We use reset browser default styles We use JS frameworks, we choose jQuery (or Zepto) We use version control tools git to collaborate on development We build front-end automation projects based on gulp to develop (which contains some information about our project structure, the third-party libraries we need to reference, etc.) We also implement sass compilation, CSS3 addition of front-end libraries, and other information. We use git, a version control tool, to collaborate on development. We use gulp to build a front-end automation project to develop (which contains the structure of our project, the third-party libraries we need to refer to, and other information, and we also automate the compilation of sass, CSS3 prefixes, and so on). We also use form validation validation plugin, lazy image loading Lazyload plugin.
2. What was one of the more difficult technical problems you encountered? How did you solve it?
3. What are the commonly used libraries? Commonly used front-end development tools? What applications or components have been developed?
4. Do you know any other technologies besides front-end? What is your best skill?
5. How do you understand the position of front-end development engineer? What are the prospects for it?
Front-end is the programmer closest to the user, closer than the back-end, database, product manager, operation, security. 1, to achieve interface interaction 2, to enhance the user experience 3, with, the front-end can achieve some of the things on the server side Front-end is the programmer closest to the user, the front-end ability is to be able to make the product from 90 points to 100 points of evolution, or even better, to participate in the project, fast and high-quality completion of the realization of the effect of the map, accurate to 1px; communication with the team members, UI design, product managers; do a good job of the page structure, page Refactoring and user experience; dealing with hack, compatibility, writing beautiful code format; optimization for the server, embracing the latest front-end technology.
6. What are your strengths? What are your weaknesses?
This article collects the major companies'Front-end Interview Questionsand provides detailedsolution. If you are preparingFront-end **interview, this article may be of help to you. Thesean interviewThe questions cover differentforward part of sth.Knowledge areas, including HTML, CSS, JavaScript, frameworks, and more. Whether you are a beginner or an experiencedforward part of sth.developers, thesean interviewThe questions can help you better understandforward part of sth.knowledge and improve their skills. In addition to providingan interviewcapacity assessmentsolutionIn addition, we have provided you with somean interviewAdvice and tips to help you inan interviewstand out from the rest. I hope this information is helpful and I wish you the best of luck!an interviewSmooth! In addition, we've included some commonan interviewissues andsolutionto help you better preparean interview. These questions can help you understandan interviewofficer's expectations of your level of understanding and skill. We also provide hands-on projects and code samples to help you better understand and master theforward part of sth.Skills. We hope that this information has been helpful and that it will help you in youran interviewWe are looking forward to your success in the future. If you have any questions or suggestions, please feel free to contact us. Good luck! If you want to further improve yourforward part of sth.skills, we recommend that you take some online courses and training programs. These courses and programs can help you gain a deeper understanding of theforward part of sth.knowledge and provide hands-on experience and feedback. In addition, we recommend that you actively participate in open source projects and communities with otherforward part of sth.Developers to network and share experiences. These opportunities can help you build your reputation.