Recommendation: two years front-end apologise from 0 to 18 k counter attack path summary | 2021 years
Like + share + comment, oh yeah!! (A portion of your base salary is spent on paid study)
(There are Easter eggs at the end of the article…) . One of my friends, an interview boy, got up at six o ‘clock every morning to study. With more than two years of experience, he got an offer of 50W. Some bosses:
-
You see a lot, the school recruit 24K cabbage price, who took the offer of the factory. You will find that they are not only highly educated, but also very hard working. I personally admire that.
-
If you want to get a big offer, you have no choice but to work on your skills. Some people can take shortcuts, but you think about whether this person is you.
1.Dear developers
In June, XU Lai concluded in the middle of the year. I got to know someone for more than two years and got an offer of 50W per year. Through acquaintance, I got to know my career plan and development direction clearly. We are halfway through the 2021 progress bar, and we have more or less experienced many, many extraordinary things happening to each other. The following interview some big factory, factory, small factory experience.
Everyone needs to have a goal, a career plan, a dream and an upward heart. (Of course, if you don’t, no one is going to make you.)
Here to thank: Hu feather big guy, byte strong brother, hao month and other big guy.
After I send my resume to them, I will only revise it once to get their approval (but I have to apply for my educational background, unless I am excellent in some aspects). I also find many gaps, so I plan to continue my study (volume).
2. Resume summary
Tao department: on resume, if have academic record hard injury, passed resume evaluation; Don’t talk too much on your resume. If the interviewer asks you what you want to know, write what you want to know. Just write about what you’ve done, technical depth, practical improvements, etc. If you have a blog, an article website, etc.
Bytes: Project experience is not a business description, but a technical highlight. Differentiate your strengths and find a good resume template. If you have less than 5 years of experience, if you can’t finish it in one page, you’re either a strong person or you’re not refined enough, so refine it to one page anyway.
Some common, you just need to write in the skills column such as: proficient in Vue technology stack, (the interviewer or HR will know that you have a basic grasp of Vue project).
Resume: Keep it short and subject matter clear.
Resume details:
- Sex name, age, work experience, contact information, education.
- Position, salary negotiable, skills, work experience (written in reverse).
- Don’t write ordinary skills, but some skills can be written as follows (just an example) :
Be familiar with JavaScript, TypeScript, Node, CSS and ES6 new features. Good at Vue technology stack, and its ecology, a framework and its implementation principle, source code 3. 4. Familiar with HTTP protocol, network principles, Webpack, Babel and so onCopy the code
- Project description, such as technology stack
Vue+Vuex+axios+element ui+echarts+es6
The development of
- (Project description, time point, problems encountered, techniques used to solve them, and results achieved)
- (Role in the project, etc., open source capability, knowledge notes, blog)
3. Small talk
- Talk about little programs, little games,
H5, APP, PC
End (I did) - How about multi-end development capability
- Website performance optimization, understand the browser implementation principle
- Browser caching, computer fundamentals, data structures and algorithms
- Browser event loop
- Front-end engineering: modularization, componentization, standardization (
eslint
Configuration, file, component, function, variable life,commit
Etc.), automation - Project catalog, specification, development process
- HTTP: Recognition of the server, three handshakes/four waves, a URL input to the browser generated interface found, etc
- The singleton pattern
- What is a closure
- What is a prototype chain
promise
–api all,race,any
, etc.async/await
- Programming ability to solve single point problems
- Architecture capability to solve complex, large project top-level design
- Engineering capacity addresses the problem of collaboration on projects involving large numbers of people
- Domain knowledge solves a set of problems for a particular business
- Ask a way:
es6
thefill,includes,find,Object.keys()
- Asked: tremble, throttling
- Ask a way:
promise
.let/const
.axios
.git flow
.branch
Branches etc. - Ask a way:
es5,es6
The inheritance of - Asked: Automation includes: unit tests,
ui
The test,CI/CD
, containerization,DockerFile
, container orchestrationk8s
monitoringsentry
HTML 5 new tags: header, sction, footer, value, nav, main, article, figure, localStorage and sessionStorage, audio/video/SVG, and so on.
CSS 3: positioning, static, relative to the find, absoulte, sticky.
4. The salary is only a ballpark.
Small and medium-sized factory:
- Primary: First-line: 7-20K; Second line: 5-15 k
- Intermediate: first-line: 15-25K; Second line: 12-23 k
- Advanced: First-line: 20-40K; Second line: 15-35 k
Giant:
- 25-50K, depending on the ability
Level (also just about)
Junior to:
- Responsible for the design and development of front-end module of business system;
- Responsible for product demand analysis, development, testing, maintenance and other work;
- Responsible for the development of FRONT-END HTML5 on PC and mobile;
- Overall page structure and CSS style layer design, optimization;
- Complete the page script programming, achieve all kinds of dynamic page, interactive effect;
- Ability to understand backend architecture and work with backend engineers to provide optimal technical solutions for projects.
Intermediate to:
- Responsible for the realization and development of project requirements;
- Complete the system detail technical design, complete the core code writing;
- Ensure requirements are met to meet project design specifications, software coding specifications and performance requirements;
- Test, system test, etc.
- Actively communicate to ensure that functionality is delivered on time and with high quality;
- Actively participate in phase reviews, meet project process quality requirements, audit and guide developers.
Satisfied, advanced development (led a small team) :
- Responsible for web front-end development of large scale systems
- Participate in technology selection, promote application and development, and support platform architecture design and development functions
- Improve the overall user experience of the system and promote the development of front-end technology
- To improve team development efficiency, refine common components, and create utility tools
- Optimize existing business and development process
- Focus on the front-end development, the application of new industry technology
- Team management
notes
Module 1:
ES6 Module Commonjs
ES6 Module
Static import, compile time importCommonjs
Dynamic import, import during execution- only
ES6 Module
In order to static analysis, implementationTree-Shaking
let apiList = require('.. /config/api.js') if(isDev) {// apiList = require('.. /config/api.js') } import apiList form '.. /config/api.js' if(isDev) {// import apiList from '.. /config/api_dev.js' }Copy the code
Scope Hosting
:
// hello.js
export default 'hello'
// main.js
import str from './hello.js'
console.log(str)
Copy the code
webpack
Performance tuning – Output code
- Small pictures
base64
coding bundle
addhash
- Lazy loading
- Provide common code
- use
CDN
To speed up - use
production
Scope Hosting
- The code volume is smaller
- Create functions with smaller scope
- Better code readability
Babel: A prerequisite for a front-end development environment. Like Webpack, you need to understand the basic configuration and usage
Environment setup and basic configuration: Babel-Polyfill, Babel-Runtime
Babelrc configuration: presets and plugins
How to use the combination of core-JS and regenerator to introduce the babel-polyfill on demand. Babel-polyfill was deprecated after Babel 7.4, and it is recommended to use core-JS and regenerator directly.
Babel-polyfill import on demand: Large file, only some features, not all, configuration import on demand.
Babel-polyfill?
- It will pollute the overall environment;
- If you do an independent
web
System, no harm; - If do a third party
Lib
, there will be problems;
Babel-runtime does not pollute the global environment:
- The basic configuration
- Advanced configuration
- Optimize packing efficiency
- Optimizing generated code
- Overview of the Build Process
babel
Segmentation:
Split configuration and merge; Start local services. Processing ES6; Handle style; Processing pictures; Multiple entry; Extracting CSS files; Extracting common code; Lazy loading; Processing JSX; Handle the Vue; Webpack optimized build speed: Optimized Babel-Loader, IgnorePlugin, noParse, happyPacK, ParalleIUglifyPlugin.
Front-end why package build, benefit?
- Smaller volume (
Tree-Shaking
, compression, merge), load faster - Compiling a high-level language or syntax (
TS, ES6+, modular, SCSS
) - Compatibility and error checking (
Polyfill, PostCSS, ESLint
)
By packaging and building, a unified, efficient development environment can be created. Unified build process and output standard, integrated company build specification (test, launch, etc.).
Module 2:
Module, chunk, bundle?
module
Each source file,webpack
Everything in the modulechunk
A combination of multiple modules, asentry
.import()
.splitChunk
bundle
The final output file
The difference between a loader and a plugin is as follows: Loader module converter, such as less-CSS; Plugin Extension plug-in, such as HtmlWebpackPlugin.
The difference between Babel and Webpack?
babel
–js
New syntax compiler tool, not concerned with modularity.webpack
– Package build tools that are multipleloader
.plugin
A collection of
How do I generate a lib? Refer to webpack.dll.js ouput Library.
Output: {// filename: 'lodash.js', // output lib to dist directory path: disPath, library: 'lodash',},Copy the code
Why can’t a Proxy be polyfilled?
- Such as
Class
You can usefunction
simulation - Such as
Promise
You can usecallback
To simulate the - but
Proxy
The function of the useObject.defineProperty
Can’t simulate
The difference between a babel-polyfill and a Babel-Runtime
babel-polyfill
It will pollute the whole worldbabel-runtime
It doesn’t pollute the whole situation- Create a third party
lib
Want to usebabel-runtime
How does WebPack implement lazy loading
import()
- In combination with
Vue React
Asynchronous components - In combination with
Vue-router``React-router
Asynchronous route loading
Webpack optimizes build speed (for production)
- To optimize the
babel-loader
IgnorePlugin
noParse
happyPack
ParalleIUglifyPlugin
Webpack optimizes build speed (not for production)
- Automatically refresh
- Hot update
- DIIPlugin
Project process
- The project is divided into multiple people and multiple roles
- The project has several phases
- Projects need to be planned and executed
Requirements analysis: understand the background, question whether the requirements are reasonable, whether the requirements are closed loop, how difficult the development is, whether other support is needed, do not rush to schedule. Technical scheme design: 1, simplify, no transition design; 2. Produced documents and duplicates; 3. Identify the key points of design and how to design components; 4. Review within the group; 5. Communicate with RD and CRD; 6. Issue conclusions of the meeting.
Complete project process: each role (demand analysis), technical scheme design, development, coordination, testing, on-line.
How to ensure code quality, development quality, project quality?
- How to feedback scheduling
- Compliance with development specifications
- Write the development document
- Write unit tests in a timely manner
Mock API
Code Review
Coordination: 1. Coordination with RD and CRD technology; 2, let UE determine the visual effect; 3. Let PM determine product functions.
Add requirements: go through the requirements change process, follow the regulations, initiate the review of the project team and leader, and reevaluate the schedule.
Test: send email, copy to project team, and record test problems in detail.
Communicate if there is a problem, QA and FE are inherently asymmetric, discuss it in person, ask QA to help you reproduce it, you need specific equipment to reproduce it. Communication, timely identification of risks, timely reporting.
Module 3:
Understand: CSS box model, DOM event class, HTTP protocol class, prototype chain class, object-oriented class, communication class, front end security class, front end algorithm class; Render mechanism class, JS running mechanism, page performance, error monitoring, business ability, team collaboration ability, with people ability.
layout
Float, Absolute positioning, Flex-box, table layout, grid layout.
<div class="left"></div> <div class="right">< div class="center"></div> div {min-height: 100px; } .left {float: left; width: 300px; background: red; } .right {float: right; . } .center { background: yellow; } Absolute Position: Absolute Flex Box grid layoutCopy the code
Basic model, content, padding, border, margin
height-content height, width-content width
Standard model, IE model difference:
- The calculated width and height are different
IE model: its width and height are calculated: padding+border.
CSS3 properties, CSS how to set these two models, box-sizing:content-box; Box-sizing :border-box (IE模 式)
JS, how to set up for the box model width and height: dom. Style. The width/height, dom. CurrentStyle. The width/height
Window.getcomputestyle (dom).width/height; dom.getBoundingClientRect().width/height
BFC(Margin Overlap Solution) Block-level formatting context: BFC principles, BFC rendering rules:
- The vertical margins of the BFC element overlap
- The area of the BFC does not overlap with the floating element’s Boxs, clearing the floating layout
- The BFC is a separate container on the page; elements on the outside do not affect elements on the inside, and elements on the inside do not affect elements on the outside
- When calculating the height of the BFC, the float element is also calculated
How to create BFC, add: overflow: hidden to parent element; ,overflow:auto; , flow is not None, set floating BFC, position: not static/relative
BFC scenarios: Resolve margin overlap and clear float. Elements of the BFC do not overlap with float elements.
DOM events: 1.DOM event level. 2.DOM event model; 3.DOM event flow; 4. Describe the specific process of DOM event capture. 5. Common applications of Event objects; 6. Customize events.
DOM event class, event level:
DOM0 element.onclick = function(){}
DOM2 element.addEventListener('click',function(){}, false)
DOM3 element.addEventListener('keyup',function(){}, false)
Copy the code
DOM event model: Capture, bubble
Event flow: When the browser interacts with the user for the current page, it clicks the icon and uploads it to the page.
Event flow: Window object, capture, Target element (Target phase) – bubble, Window object.
Describe the specific process of DOM event capture: window-document-html-body-target element. (document.documentElement)
An Event object is an Event object.
Event.preventdefault () preventDefault behavior; Event.stoppropagation () To stop bubbling behavior; Event. StopImmediatePropagation (); Event.currenttarget, the current bound event; The event target.
Custom events:
var eve = new Event('custome'); ev.addEventListener('custome',function(){ console.log('custome'); }); ev.dispatchEvent(eve); window.addEvenListener('click', function(){}, true); // The capture phase triggersCopy the code
Module 4:
The HTTP protocol:
- Main features of THE HTTP protocol
- Component of an HTTP packet
- HTTP method
- The difference between POST and GET
- The HTTP status code
- What is a persistent connection
- What is pipetization
Component of an HTTP packet
Request message: request line, request header, blank line, request body; Response message: status line, response header, blank line, response body. Request line contains: HTTP method, page address, HTTP protocol and version; The request header contains the key-value value, which tells the server what I want.
The main characteristics of THE HTTP protocol class: simple and fast, flexible, connectionless, stateless.
HTTP protocol class, HTTP methods: GET, obtain resource, POST, transfer resource, PUT, update resource, DELETE, DELETE resource, HEAD, obtain packet header.
HTTP protocol: THE differences between POST and GET are as follows: 1.GET is harmless when the browser rolls back, while POST will submit the request again. 2. The URL generated by GET can be favorites, but POST cannot. 3.GET requests are cached by the browser, but POST requests are not, unless manually set. 4.GET requests can only be encoded by URL, while POST requests can be encoded in multiple ways. 5.GET request parameters are completely preserved in the browser history, while POST parameters are not; 6. The parameters sent by GET request in THE URL are limited in length, while POST is unlimited; 7. For the data type of parameters, GET accepts only ASCII characters, while POST has no restrictions; 8.GET is less secure than POST because parameters are directly exposed in the URL, so it is not used to pass sensitive information; 9. The GET parameter is passed through the URL, and the POST is placed in the Request body.
HTTP status code:
1xx
: indicates that the request has been received and processing continues;2xx
: Successful: The request is successfully received.3xx
: redirection, which requires further action to complete the request4xx
: Client error, request syntax error or request cannot be implemented;5xx
: Server error, the server could not implement a valid request.200
Ok: The client request succeeds206 Partial Content
: The client sends a GET request with a Range header and the server completes it301 Moved Permanently
: The requested page has been moved to a new URL302 Found
: All requested pages have been temporarily moved to a new URL304 Not Modified
: The client has cached documents and has made a conditional request
The server tells the client that the cached document can still be used
400
The client request has a syntax error and cannot be understood by the server401
The request is unauthorized. This status code must matchwww-Authenticate
Header field403
Access to the requested page is denied404
The requested resource does not exist505
The server sends an unexpected error, and the cached document is still available503
Requests are not completed, the server is temporarily overloaded or down, and may return to normal after some time
Persistent connections: HTTP1.1 version 1.0 not supported
The HTTP protocol adopts the “request-reply” mode. When the common mode is used, that is, the keep-alive mode is not used, each request/reply client and server need a new key to connect, and the connection is disconnected immediately after completion (HTTP is a connectionless protocol).
When using keep-alive mode (also known as persistent connection, connection reuse), the keep-alive function makes the connection from the client to the server valid and prevents the connection from being established or reestablished in the event of a subsequent request to the server.
Pipelines:
- In the case of non-persistent connections, message delivery over a connection is similar to request 1-response 1
- With persistent connection: Request 1-Request 2-response 1-response 2
Pipelines:
- Pipelining is done through persistent connections, which is only supported by HTTP1.1
- Only GET and HEAD requests can be piped; POST is limited
- The pipeline mechanism should not be enabled when the connection is first created because the other party (server) does not necessarily support the HTTP/1.1 protocol
- Pipelining does not affect the order in which the response arrives, and the order in which the response returns does not change
- HTTP/1.1 requires that the server be piped, but it does not require that the server also manage the response, only that the piped request does not fail
- Because of the server-side issues mentioned above, it is unlikely that having pipelining enabled will provide a significant performance boost, and many server-side and proxy applications do not support pipelining well, so modern browsers such as Chrome and FireFox do not have it enabled by default
Prototype chain class: create object several methods, prototype, constructor, instance, prototype chain, instanceof principle.
There are several ways to create an object:
Var o1 = {name:'o1'}; var o2 = new Object({name:'01'}); Var m = function(){this.name='01'} var m1 = new m(); // Object.create var p = {name:'o3'}; var o3 = Object.create(p);Copy the code
The prototype chain:
Constructor, new, instance, constructor – prototype-object, prototype object, constructor, instance __proto__ to the prototype object.
Prototype chain: instance object proto – instanceof – prototype – instance object -constructor -constructor.
Module 4:
The new operator:
- A new object is created, which inherits from
foo.protoype
. - The constructor foo is executed. When executed, the corresponding call is passed in, and the context (
this
) will be specified as this new instance,New foo is the same as new.foo()
“Can only be used when no arguments are passed. - If the constructor returns an “object,” then that object replaces the entire result of new. If the constructor does not return an object, then the result of new is the object created in step 1.
Classes and instances: declarations of classes; Generate an instance.
Classes and inheritance: how to implement inheritance; Several ways of inheritance.
Class declaration:
function Animal() { this.name = 'name'; } // es6 class class Animal2 { constructor() { this.name = name; }}Copy the code
The essence of inheritance the archetypal chain:
- Inheritance is implemented with constructors
function Parent1() {
this.name = 'parent';
}
function Child() {
Parent.call(this);
this.type = 'child';
}
Copy the code
The downside is that you can’t get methods on the prototype superclass constructor.
- Inheritance with prototype chain
function Parent2() {
this.name = 'parent2';
}
function Child2() {
this.type = 'child2';
}
child2.prototype=new Parent2();
Copy the code
The disadvantage of the prototype chain inheritance is that the prototype objects in the prototype chain, which reference the same object, are instance objects of the parent class.
The third inheritance mode: combination mode
function Parent3() { this.name = 'parent3'; This. Play = [1, 2, 3]; } function Child3() { Parent3.call(this); this.type = 'child3'; } Child3.prototype = new Parent3(); var s3 = new Child3(); var s4 = new Child4(); s3.play.push(4);Copy the code
The drawback is that the parent constructor is executed twice.
Fourth way: combined with inheritance optimization, inherit the prototype object of the parent class (the original type)
function Parent4() { this.name = 'parent4'; This. Play = [1, 2, 3]; } function Child4() { Parent4.call(this); this.type = 'child4'; } constructor = constructor; // constructor = constructor; // constructor = constructorCopy the code
Fifth, combination inheritance
function Parent5() { this.name = 'parent5'; This. Play = [1, 2, 3]; } function Child5() { Parent5.call(this); this.play = 'child5'; } Child5.prototype = Object.create(Parent5.prototype); // __proto__ Child5.prototype.constructor = Child5; // The constructor points to Child5Copy the code
- DNS:
Root DNS, top-level DNS, authoritative DNS, local DNS, load balancing
. - Lower layer protocol: Reliable data transmission, layer 4 and layer 7,
TCP/IP, UNIX Domain Socket
. - Proxy: Forward Proxy, reverse Proxy, Proxy protocol.
URI/URL
: Indicates the protocol name, query parameters, and code.webSocket
: Full duplex, binary frame, stateful.- Code:
Base64, Chunked, Compressed (Gzip, deflate)
- Packet capture tools:
Wireshark, tcpdump
- HTTP / 3: based on
UDP, QUIC, gRPC
- HTTP/2:
HPACK,Server Push,SPDY
- HTTPS: Symmetric encryption (
AES,ChaCha
), asymmetric encryption (RSA, DH
), the summary algorithm (SHA-2
), certificate (X509,CA
),SSL/TLS
(SNI,OCSP, connection optimization). CDN
(Load balancing, proximity access,Squid/Varaish/ATS
WAF
: Application layer protection, access control, audit
TCP Three-way handshake: SYN, SYN.ACK, ACK; TCP four-way handshake closes the connection: FIN, ACK/FIN, ACK
Module 5:
- What are same-origin policies and restrictions
- How do the front and back ends communicate
- How to Create Ajax
- Several ways of cross-domain communication
What are same-origin policies and restrictions
Same-origin policies restrict how documents or scripts loaded from one source interact with resources from another source. This is a key security mechanism for isolating potentially malicious files.
- Cookie, LocalStorage, IndexDB cannot be read
- DOM cannot fetch
- The AJAX request could not be sent
AJAX is the communication mode under the same origin. WebSocket does not limit the same origin policy. CORS supports cross-source communication and same origin communication.
How to Create Ajax
XMLHttpRequest
Object workflow- Compatibility handling
- Conditions for triggering an event
- The sequence in which events are triggered
Object.prototype.toString.call()
var util = {}; util.indexOf = function(array, item) { for(var i=0; i<array.length; i++) { if(array[i] === item) { return i; } } return -1; }; / / determine whether for function util. IsFunction = function (source) {return "[Object function] ` = = = Object. The prototype. ToString. Call (source)} / / determine whether util. Ie isIE = function () {var myNav = the navigator. UserAgent. ToLowerCase (); return (myNav.indexOf('msie') ! = = 1)? parseInt(myNav.split('mise')[1]) : false; };Copy the code
Simulation of Ajax functionality:
util.json = function(options) { var opt = { utl: '', type: 'get', data: {}, success: function() {} error: function() {} }; util.extend(opt, options); if(opt.url) { var xhr = XMLHttpRequest ? new XMLHttpRequest() : new window.ActiveXObject('Microsoft.XMLHTTP'); var data = opt.data, url = opt.url, type = opt.type.toUpperCase(), dataArr=[]; for(var k in data) { dataArr.push(K+'='+data[k]); } if(type === 'GET') { url = url + '? ' + dataArr.join('&'); xhr.open(type, url.replace(/\? $/g, ''), true); xhr.send(); } if(type === 'POST'){ xhr.open(type, url, true); xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); xhr.send(dataArr.join('&')); } xhr.onload = function() { if(xhr.status === 200 || xhr.status === 304) { var res; if(opt.success && opt.success instanceof Function) { res = xhr.responseText; if(typeof res === 'string') { res = JSON.parse(res); opt.success.call(xhr.res); } } }else{ if(opt.error && opt.error instanceof Function) { opt.error.call(xhr.res); }}Copy the code
There are several ways of cross-domain communication:
JSONP
Hash
PostMessage
WebSocket
CORS
The principle of JSONP:
util.jsonp = function(url, onsuccess, onerror, charset) { var callbackName = util.getName('tt_player'); window[callbackName] = function() { if(onSuccess && utils.isFunction(onSuccess)) { onSuccess(arguments[0]); }}; var script = util.creatScript(url+'&callback='+callbaseName,charset); script.onload = script.onreadystatechange = function() { if(! script.readyState || /loader|complete/.test(script.readyState)){ script.onload = script.onreadystatechange = null; / / remove the script DOM object if (script. ParentNode) {script. ParentNode. RemoveChild (script). } window[callbackName] = null; }}; script.onerror = function() { if(onerror && util.isFunction(onerror)) { onerror(); }}; <script SRC ="http://xxx.com/?data = name & callback = 'jsonp'charset = 'utF-8 '></script>Copy the code
<script>
jsonp({data:{}})
</script>
Copy the code
Using webSocket is not restricted by the same origin policy:
var ws = new WebSocket('wss://echo.websocket.org');
ws.onopen = function(evt) {
console.log('');
ws.send('');
};
ws.onmessage = function(evt) {
console.log('');
ws.close();
};
ws.onclose = function(evt) {
console.log('');
};
Copy the code
Module 5:
CSRF, XSS-CSRF: Commonly referred to as cross-site request forgery
Cross-site-request forgery CSRF, attack principle, and defense measures.
CSRF defense measures: 1. Token authentication. 2. Referer validation; 3. Hide the token
CSRF attack principle: The user clicks to log in, sends cookies, and seduces the user to click and access the API interface of website A, especially the GET type. After the registration is successful, there is no manual upload of the token, and the attack is avoided without the token. Referer validates the source of the page, whether it is from a page under my site. If yes, it performs the action, if not, it intercepts.
Xss-cross-site scripting Cross-domain script attacks: XSS scripting: Injects scripts to pages and takes defensive measures to prevent script execution
Differences between XSS and CSRF
XSS
Is to inject into your pageJS
To execute, and then do whatever it wants in the body of the JS functionCSRF
By exploiting your own vulnerabilities to help you proactively implement those interfaces, CSRF relies on you as a user to log in to the site
Algorithm: heap, stack, queue, linked list; JS array itself has the characteristics of heap, stack, queue, push, pop, shift, unshift
Stack: first in, first out, first in, unshift in,pop out.
Apply colours to a drawing mechanism
- What is the
DOCTYPE
And the role of - Browser Rendering process
- rearrangement
Reflow
- redraw
Repaint
- layout
Layout
A DOCUMENT Type Definition (DOCUMENT Type Definition) is a set of syntax rules that define file types for XML or (X) HTML. Browsers use it to determine the document type, decide which protocol to use for parsing, and switch browsing modes.
Doctypes are used to declare document types and DTD specifications. One of the main uses of doctypes is to verify the validity of files. If the file code is invalid, the browser will have some errors when parsing it.
Browser rendering process
HTML,HTML Parser,DOM Tree(DOM) (Style sheets-> CSS Parser-> Style Rules)->Attachment->Render Tree(Layout)->Painting->Display
Reflow rearrangement
Definition: Each element of a DOM structure has its own box (model), which requires the browser to calculate according to the various styles and place the element where it should appear, a process called reflow.
Trigger reflow:
- Reflow or Repaint occurs when you add, remove, or modify DOM nodes.
- When you move the DOM, or when you animate it
- When you change CSS styles
- When you Resize the window (not a problem on mobile), or when scrolling
- When you change the default font on a web page
Redraw Repaint
When the location, size, and other attributes such as color and font size of the boxes are determined, the browser then paints each element with its own characteristics, and the content of the page appears. This process is called repaint.
Operation mechanism: JS single thread, a time, JS can only do one thing; EventLoop indicates the EventLoop.
Task queue: synchronous task, asynchronous task.
Page performance
Ways to improve page performance:
- Resources are compressed and merged to reduce HTTP requests
- Non-core code is loaded asynchronously, the way it is loaded asynchronously,
- Use the browser cache
- Use the CDN
- Preliminary analytical DNS
<meta http-equiv='x-dns-prefetch-control` content='on'>
<link rel = 'dns-prefetch' href="//host_name_to_prefetch.com'>
Copy the code
CDN- allows the network to quickly reach the server and download the file, especially when the page is first opened, the browser cache is not of any use, so the use of CDN is very obvious.
Preresolve DNS, if your page uses multiple domain names, your DNS resolution is very obvious.
- Everything in the page
a
TAB, which is opened by default in some advanced browsersDNS
Pre-parsed, which means you don’t have to addmeta
Wait, wait, waitDNS
Pre-parsed, but if your page ishttps
Protocol start, many browsers are closed by defaultDNS
If it is preparsed, it must be forcibly openedDNS
Parsing.
- Non-core code is loaded asynchronously
- Use the browser cache
Asynchronous loading mode: dynamic script loading; Defer. async
The difference between asynchronous loading:
defer
Is in theHTML
It is executed only after the parsing is complete. If it is multiple, it is executed in the order in which it was loaded.async
Is executed immediately after loading, if multiple, the order of execution is independent of the loading order.
Module 6:
Browser cache:
Cache classification: strong cache/negotiated cache
Expires thXXX cache-control: max-age // Last-modified/if-modified-since Etag/ if-none-matchCopy the code
The browser cache refers to the backup, or copy, of your resource file that exists in the browser.
A strong cache is when I don’t ask, I don’t ask, I just get it and use it; Negotiation caching is when the browser finds out that I have a local copy of this file, but I’m not sure if I want to use it, so I ask the server if I want to use this file, so I negotiate with the server whether I can use this file, whether it’s expired, and this process is called negotiation caching.
Strong cache: Expires: indicates the expiration time. The value indicates the absolute time. Cache-control: cache-control :max-age=3600 relative time.
Negotiation cache: last-modified time of Last modification, if-modified-since request, Etag solution: resources below the server will give you the Etag value, if-none-match.
1.0 disadvantages: although my time has changed, but my content has not changed, the content has not changed, I can completely take from the copy.
1.1 After the strong cache time, the browser asks the server If it can use the resource again, it will use if-none-match, HTTP will add an if-none-matchkey, and then add a value, The value is the Etag value under the server.
Caching is optimized to improve page performance.
Understand the error monitoring classes: the classification of front-end errors, how errors are caught, and the basic principles of error reporting. Classification of front-end errors: real-time run errors, code errors, resource loading errors. Real-time run errors are caught by: try… catch… , window. Onerror
Resource loading Error: object.onError, performanc.getentries (), Error event
The basic principles for reporting errors are as follows: 1. Report errors using Ajax communication. 2. Report the Image object.
- Business ability
- Ability to think
- The ability to learn
- pay
Module 7:
Vuex is an ecosystem designed for Vue to manage the data status of pages and provide unified data operations. It focuses on the Model layer in THE MVC pattern, which stipulates that all data operations must be carried out through the process of action-mutation-state and change, and then combined with the bidirectional binding feature of Vue’s data view to realize the display and update of the page.
Unified page state management and operation processing can make complex component interaction simple and clear. At the same time, you can perform backward operation like a time machine in debugging mode to view the process of data change, which makes code debug more convenient.
Vue Components – Dispath – Actions – commit – Mutations – Mutate – State – Render.
- Vue Components, Vue Components, HTML page, responsible for receiving user operations and other interactive actions, execute the disPATH method to trigger the corresponding action for response.
- Dispath, the action behavior triggering method, is the only method that can execute an action.
- Actions, which processes all interactions received by Vue Components, including synchronous/asynchronous actions, supports multiple methods of the same name, and is triggered in the order in which it was registered. The operations requested to the background API are performed in this module, including triggering other actions and submitting mutation operations. This module provides encapsulation of promises to support chained triggering of actions.
- Commit, the method of committing an operation when the state changes. Submitting the mutation is the only way to execute the mutation.
- Mutations: Operation method of state change, which is the only way for Vuex to modify state. Other modification methods will report errors in strict mode. This method can only perform synchronous operation, and the method name can only be globally unique. During the operation, some hooks will be exposed for state monitoring and so on.
- State: Page state management container object. The scattered data of data objects in Vue Components is stored in a centralized manner, which is globally unique for unified state management. The data required for the page display is read from this object, utilizing Vue’s fine-grained data response mechanism for efficient status updates.
- Getters: State object reading method. This method is used to read the global state object in render.
Life Cycle flow chart
New Vue Creates a new Vue instance, initializes (event & lifecycle), beforeCreate, initializes (injection & validation), created, does the ‘EL’ option exist? Yes, whether to specify the ‘template’ option, yes (to compile the template into the render function), no (to compile HTML outside the EL as a template); BeforeMount: Creates vm.$EL and replaces EL, mounted. BeforeUpdate, when data is modified, the virtual DOM is rerendered and updated. When vm.$deStory is called, beforeDestory, unbind and destroy child components and event listeners, destoryed.
Life cycle Before and after creation, before/after mount, before/after update, before/after destruction.
beforeCreate
In thebeforeCreate
When the life cycle is executed,data
andmethods
The data in is not initialized, so it cannot be used at this timedata
Data inmethods
Method in.created
.data
andmethods
After the initialization is complete, it can be usedmethods
Method anddata
Data in.beforeMount
.template
The template has been compiled, but has not yet been mounted to the page, which is still in the previous state.mounted
At this point, the Vue instance is initialized and the DOM is mounted. You can directly operate the DOM or use third-party DOM libraries.beforeUpdate
At this point, data has been updated but the page has not been synchronized.updated
.data
And pages have been updated.beforeDestory
, the Vue instance enters the destruction phase, but all data and methods, instructions, filters, etc. are still available.destoryed
At this point, the component has been destroyed, data, methods, etc are not available.
[v-cloak]{display: None} = [v-cloak]; [v-cloak]{display: None} = [v-cloak];
Communication schemes between components, and between fathers and sons:
- By event bus, that is, by publish subscribe
- vuex
- The parent component transfers data to the component through prop
- The child component is bound to a custom event
this.$emit(event.params)
To invoke custom events - Use what vue provides
parent children
&refs
Method to communicate
The on-demand loading of components is part of the optimization of the project and also reduces the first screen rendering time; Use () = > import (); Use resolve = > the require ([‘. / component], resolve)
Keep-alive is a built-in component of Vue that keeps state in memory during component switching, preventing repeated DOM rendering. Chunk is a collection of Modules in the WebPack packaging process, a concept in the packaging process.
Json: Ajax requests are affected by the same origin policy, does not allow for cross-domain request, and scripts to the links in the SRC attribute can visit cross-domain Js script, using this feature, the server no longer return JSON format of the data, but some function returns a call of Js code, in SRC has carried on the call, so that achieve the cross-domain.
Fibonacci series:
function f(n) { if(n===0){ return 0; }else if(n===1){ return 1; }else{ var fn1 = 0; var fn2 = 1; var fnx = 0; for(var i = 0; i< n-1; i++) { var newFn = fn2; fnx = fn1+fn2; fn1 = fn2; fn2 = fnx; } return fnx; }}Copy the code
Recursive algorithm:
function fib(count) {
var count = parseInt(count);
if(isNaN(count) || count<=0) {
return 0;
}
function f(count) {
if(count<=2) {
return 1;
}
return f(count-1)+f(count-2);
}
return f(count);
}
Copy the code
Find the first 20 numbers:
var arr = [];
arr[1] = 1;
arr[2] = 2;
for(var i = 3; i<20; i++) {
arr[i] = arr[i-1] + arr[i-2];
}
for(var i = 1; i<arr.length; i++) {
console.log(arr[i]);
}
Copy the code
Module 8:
Vue implements bidirectional data binding:
Implements a listener Observer that traverses data objects, including property objects, with setters and getters using the object.defineProperty () property. In this case, if you assign some value to this object, that triggers the setter, so you’re listening for changes.
Implement a parser Compile, parse the Vue template instructions, replace the template iterations with data, and then initialize the rendering page view, and bind the corresponding nodes of each instruction to update functions, add subscribers to listen to data, once the data changes, receive notification, call update functions to update data.
Implement a subscriber Watcher:Watch subscribers serve as a communication bridge between The Observer and Compile. Their main task is to subscribe to messages about attribute changes in the Observer. When they receive a message about attribute changes, they trigger the corresponding update function in the parser Compile.
Implement a subscriber Dep that uses a publish-and-subscribe design pattern to collect subscriber Watcher and manage the listener Observer and subscriber Watcher in a unified manner.
algorithm
- Stack, last in, first out,
Push and pop
- Queue, first in first out,
Push to the shift
- Linked lists, nodes, do not know the memory address of the element (each node structure consists of two parts of content, data field and pointer field)
Example:
{val: 2, next:... }} function ListNode(val) {this.val = val; this.next = null; }Copy the code
- Binary tree: root, child, and leaf; Leaf node height is not 1, equal to the height of the tree; Degree means how many subtrees a node branches off, and is denoted as the degree of the node; If the degree is zero, it’s a leaf.
- Binary tree structure: 1. It can exist as an empty tree without a root. 2, if it is not an empty tree, then it must consist of the root, the left subtree and the right subtree and the left and right subtrees are binary. 3. A binary tree cannot be simply defined as a tree whose degree of each node is 2.
Binary tree: In JS, binary tree is defined by objects, and its structure is divided into three blocks:
- Data fields
- A reference to the child node on the left
- A reference to the child node on the right
Binary tree node constructors:
function TreeNode(val) { this.val = val; this.left = this.right = null; } // Const node = new TreeNode(1);Copy the code
Binary tree traversal: 1. First order traversal, 2. Middle order traversal, 3.
Depending on the implementation: recursive traversal; Iterated traversal (in-order traversal, hierarchical traversal)
Create a node consisting of the data field, left and right subtrees, and each binary tree should consist of all three parts.
Recursive function (recursive expression, recursive boundary)
Function preorder(root) {// root is null if(! Root) {return} console.log(' value of the node currently traversed '+ root.val); // Recursively traverse the left subtree: preorder(root.left); // Recursively traverse the right subtree: preorder(root.right); } function inorder(root) {if(! Root) {return} inorder(root.left); Console. log(' currently traversed node is ', root.val); Inorder (root.right); } function postorder(root) {if(! Root) {return} // recurse through the left subtree postorder(root.left) // recurse through the right subtree postorder(root.right) // output the values of the nodes currently traversed console.log(' the values of the nodes currently traversed are: '+root.val)} Time/space complexityCopy the code
- Time: a trend in the total number of times an algorithm is executed
- Space: The trend of memory growth
Sum two numbers
const twoSum = function(nums, Const diffs = {} // Cache array length const len = nums.length // Traversing array for(let I = 0; i<len; I ++) {if(diffs[target-nums[I]]! Get return [diffs[target-nums[I]], I]} == diffs[nums[I]= I}}Copy the code
Merge two ordered arrays:
Const merge = function(nums1, m, nums2, n) {let I = m-1, j = n-1, k = m+n-1; While (I >=0 && j>=0) {if(nums1[I] >= nums2[j]){num1[k] = nums1[I] I --; k--; }else{ num1[k] = nums2[j] j--; k--; }} while(j>=0){nums1[k] = num2[j];}} while(j>=0){nums1[k] = num2[j]; j--; k--; }};Copy the code
String: Invert string:
const str = 'huang'; Const res = str.split(").reverse().join("); console.log(res);Copy the code
Palindrome strings: Read forwards and backwards
Function isPalindrome(STR) {const reversedstr = str.split(").reverse().join("); return reversedstr === str }Copy the code
Having symmetry:
Function isPalindrome(STR){const len = STR. Length // for(let I = 0; i<len/2; i++) { if(str[i] ! == str[len-i-1]){ return false } } return true }Copy the code
Merging lists:
Const mergeTwoLists = function(l1,l2) {let head = new ListNode() let cur = head; While (l1&&l2) {if(l1. Val <= l2.val) {next = l1. Next = l1 L1. next}else{// l1.next = l2.next}else{// l2.next = l2.next} Cur. next = l1! Next = cur.next = l1! == null ? Return head. Next}Copy the code
The singleton pattern
Class SingleDog{show() {console.log(' I'm a singleton ')} static getInstance() {if(! SingleDog.instance) { SingleDog.instance = new SingleDog() } return SingleDog.instance } }Copy the code
Closure:
Singledog.getinstance = (function() {let instance = null return function() {// Check whether free variables are null if(! instance) { instance = new SingleDog() } return instance } })()Copy the code
Vue principle:
- Componentization and MVVM data-driven views
- Response principle
- Vdom and DIFF algorithms
- Template compilation/update
- Component Rendering Process
- The front-end routing
Routing mode: Hash/History; Route configuration: dynamic route/lazy load
Component rendering process: 1. Initial rendering process, 2. Update process, 3.
The render function generates vNode, path(elem, newNode), path(elem, newNode), and path(ELEm, newNode). Modify data, trigger setter, update execute render function to generate newNode; $nextTick, summarize data modification, update view once, reduce DOM operation times, improve performance.
Routing mode: Hash changes trigger page redirection that is, the browser moves forward and back. Hash changes do not refresh the page. A necessary feature of SPA: the hash is never submitted to the server.
Principle of history performance: using the url routing, but when to jump, refresh the page, history. PushState, window. Onpopstate
Componentization: Componentization history, data-driven view, MVVM. Responsive: Object.defineProperty, listening on objects (depth), listening on arrays, shortcomings of Object.defineProperty, vue.set, vue.delete, native arrays.
Vdom and DIFF: Vnode structure, Snabbdom degree. Template compilation: with syntax, the template is compiled to render function, execute render function to generate vNode.
$emit = props/this.$emit = props /event.$off/event.
The implementation principle of two-way data binding V-Model:
input
Elements of thevalue=this.name
- The binding
input
Events:this.name = $event.target.value
date
Update trigger:re-render
Computed features: The data is cached, improving performance. When to use asynchronous components: Load large components, load them asynchronously. When to use deforeDestory, unbind custom events: event.$off, clear timer, unbind custom events.
Vue optimization:
- The rational use of
v-show
andv-if
- The rational use of
computed
v-for
When to addkey
In order to avoid andv-if
Simultaneous use (v-for
Make it a higher priority, every timev-for
You need to usev-if
, these capabilities are a drain.)- Custom events,
DOM
Event timely destruction - Use asynchronous components wisely, use them wisely
keep-alive
.data
Don’t go too deep - use
vue-loader
, do compilation (precompilation) in the development environment, front-end general performance optimizations such as lazy image loading, use SSR.
What is concurrent/parallel
- Concurrency is when a processor processes more than one task at a time.
- Parallelization is when multiple processors or multi-core processors work on multiple different tasks at the same time.
- Concurrency is logical simultaneity, parallelism is physical simultaneity.
- Concurrent is a person eating three steamed buns at the same time, while parallel is three people eating three steamed buns at the same time.
Garbage collection: 1. reference counting garbage collection. 2. Mark-clear.
Find duplicate elements in the data:
function fun(arr) {
var a = arr.sort();
var result = [];
for(var i = 0; i < arr.length; i++) {
if(arr[i] === arr[i+1] && result.indexOf(arr[i]) == -1) {
result.push(arr[i]);
}
}
return result;
}
Copy the code
New operation:
var obj = new Da();
var obj = {};
obj.__proto__ = Da.prototype;
Da.call(obj);
Copy the code
Simple antiskid function debounce, the principle of implementation:
The debounce function is a function that executes only once, no matter how many callbacks are fired within a certain period of time. If we set up a function with a wait time of 3 seconds, if we get a function call request within that 3 seconds, we will time it again for 3 seconds, until there is no call request within the new 3 seconds, at which point we will execute the function, otherwise we will time it again and so on.
The implementation principle is to use the timer. When the function is executed for the first time, a timer is set. When the function is called later, if the timer has been set, the previous timer is cleared and a new one is set. If there is a timer that has not been cleared, the function execution is triggered when the timer ends.
Judge:
instanceOf
Constructor
Object.prototype.toString.call()
Inheritance I summarized: there are 1, prototype chain inheritance, 2, borrow constructor inheritance, 3, combination inheritance, 4, primitive type inheritance, 5, parasitic inheritance, 6, parasitic combinatorial inheritance. Class and extends are new in ES6 to define classes and implement inheritance, with parasitic combinational inheritance at the bottom.
This points to the question:
- This refers to the person who calls the function in which this is located
- Write this directly to the fn function. (If you write this directly to the fn function, the value of this will be determined by its context, usually pointing to window
onclick
This in the event
Through:
Object.keys(obj)
Object.values(obj)
The more you know, the more you will consider.
❤️ follow + like + collect + comment + forward ❤️, original is not easy, encourage the author to create better articles
Like, bookmark and comment
I’m Jeskson, thanks to all the talented people: likes, favorites and comments, we’ll see you next time! ▌ I have to show you the truth. ▌ I have to show you the truth. I have to show you the truth.
Personal website: 1024bibi.com/
See you next time!
Welcome to Star: github.com/webVueBlog/…
Special note: please add at the end of the article: the nuggets years | 2021 theme activities I grow half of the campaign is under way on the road…