Foreword: hope can pass this article, can give you get help. (thanks for three keys), the front end of the white constantly upgrade play strange…
HTML
1. How to understand HTML semantics?
Semantically make code readable (makes code easier to read) search engines, easy to separate pages
2. By default, which HTML tags are block-level and which are inline?
- Display: block/table; Div, H1, table, UL, OL, P, etc
- Display: inline/inline – block; Span, IMG, input button, etc
CSS
layout
1. Box model
#div {
width: 100px
padding: 10px
margin: 10px
border: 1px solid $ccc
}
Copy the code
Offsetwidth = (content width + inner margin + border), no outer border
Default: box-sizing: content-box;
122
Set up the
The box – sizing: border – box
100
2. The problem of longitudinal overlap of margin
p {
margin-top: 10px;
margin-bottom: 15px;
}
<p>AAA</p>
<p></p>
<p></p>
<p></p>
<p>BBB></p>
Copy the code
Margin-top and margin-bottom of adjacent elements will overlap blank content
3. The problem of margin negative value
- Margin-top /margin-left elements move up and left
- Margin-right is a negative value, and the right element moves to the left, not affecting itself
- Margin-bottom: The bottom element moves up without affecting itself
4. BFC understanding and application
BFC block-level formatting context
Common conditions for BFC formation:
- Float is not none
- Position is absulute or fixed
- Overflow is not visible
- Dispaly is Flex inline-block etc
Common BFC applications: Clearing floating
5. Float layout issues, and ClearFix
How to achieve the holy cup layout and the twin wing layout?
Objective:
A three-column layout, with the middle column loading and rendering first (content is most important) and the two sides of the content fixed, the middle content ADAPTS to the width is generally used on PC web pages
Technical Summary:
Use margin negative values on both sides of a float layout to overlap the middle content horizontally and prevent the middle content from being overwritten by both sides, one padding and one margin
Grail layout: Padding
Double wing layout: Margin
Handwritten clearfix?
.clearfix:after{
content: ' ';
display: table;
clear: both
}
.clearfix {
*zoom: 1; /* Compatible with earlier VERSIONS of IE */
}
Copy the code
6. Flex paint dice
Flex implements a three point dice?
flex-direction
Justify -content // Spindle alignment
align-items
Flex-wrap // Whether to wrap a line
Align-self // cross the axis
positioning
absolute relative
7. What is absolute and relative?
- Relative refers to its position
- Absolute Absolute relative fixed based on the location element of the nearest layer
8. What are the implementation methods of center alignment?
- Horizontal center
Inline element: text-align: center
Block element: margin: Auto
Absolute element: left: 50% + margin-left negative
- Vertical center
Inline element: line-height equals height
Absolute element: top: 50% + margin-top negative prerequisite: know the height and width of the child element
Absolute element: transform: translate(-50%, -50%) Compatibility problem
Absolute: top, left,bottom, right = 0 + margin: auto
9. Line-height inheritance problem
Write a specific value, such as 30px, and inherit it
Font-size *1.5 = 24px font-size*1.5 = 24px
Font size * line-height % 20* 200% = 40px
Font-size: 20px word-break: break-all200%} p{font: 16px}Copy the code
The line height of the p label is 20*200% = 40px
Graphic style
responsive
10. What is REM?
Rem is a unit of length
Px: absolute unit of length, most commonly used
Em: unit of relative length, relative to parent element, not commonly used
Rem: Unit of relative length, relative to the root element, often used in reactive layouts
HTML {font size: 100px} div {font size:0.16rem
}
Copy the code
A common solution for responsive layout? Media-query, which sets the font-size rem of the root element according to the different screen widths, based on the relative units of the root element
Max-width: 374px —- HTML {font-size: 86px}
Iphone6/7/8 and iphonex min-width: 374px and max-width: 413px —- HTML {font-size: 100px}
Min-width: 414px —- HTML {font-size: 110px}
Font-size: 0.16rem; }
Disadvantages of REM: ladder type
Page viewport size
Window.screen. height // Screen height
Window. innerHeight // The viewport height of the web page goes from top to bottom
Document. Body. ClientHeight / / body height
vw/vh
Vw page viewport width 1/100
Vh web page viewport height 1/100
Vmax takes the maximum value of both; Vmin takes the minimum value of both — landscape
JS
1. Typeof determines which types
Identify all value types
Identification function
Determines whether to reference the type (non-subdivided) Object
2. = = = = =
3. The difference between value types and reference types
Value type: Number String Boolean undefined Symbol
Reference type: null array object function
4. Write deep copies
Variable type reference type Typeof operator
Deep copy
5. Type conversion
String splicing
= =
If statements and logical judgments
Falsely variable
!!!!! 0 === false
!!!!! NAN === false
!!!!! null === false
!!!!! undefined === false
!!!!! false === false
6. Prototypes and prototype chains
7. Class and inheritance
constructor
attribute
methods
Extends inheritance
Super parent class
Extension to rewrite
8. Check the instanceof type
Determining the reference type
Object is the parent class of all reference types
[] instanceof Array // true
[] instanceof Object // true
{} instanceof Object // true
9. The prototype
Class is actually implemented by function
proto
prototype
Look for properties and methods in yourself first
If it can’t find it, it automatically looks for __proto__
The prototype chain
11. Scopes and closures
How do I value different scenarios of this?
Handwritten bind
Closure application scenarios in real development?
Scope and free variables
Global scope, function scope, block-level scope
Free variable:
Definition:
- A variable is not defined in the current scope, but is used
- Search through the upper scope, layer by layer, until you find it
- If the global scope is not found, xx is not defined
Closure:
The special case of scope application has two manifestations:
Functions are passed as arguments
The function is returned as the return value
The function is returned as the return value
function create() {
const a = 100
return function() {
console.log(a)
}
}
const fn = create()
const a = 200
fn() / / 100
Copy the code
Functions are passed as arguments
Closure: The search for free variables is in the function definition, in the parent scope, not in the execution place
function print(fn) {
const a = 200
fn()
}
const a = 100
function fn() {
console.log(a)
}
print(fn) / / 100
Copy the code
This:
As a general function
Use call Apply bind
Called as an object method
Called in the class method
The arrow function this takes the value of the parent scope
What value should this take when the function is executed, not when it is defined
The bind:
Function.prototype.bind2 = function() {
const args = Array.prototype.slice.call(arguments)
const t = args.shift() // First args remaining argument
const self = this
return function() {
return self.apply(t, args)
}
}
function fn(a, b) {
console.log(this)
console.log(a, b)
}
const fn2 = fn.bind2({ a: 2},2.3 )
fn2() // { a: 2 } 2 3
Copy the code
Closure application:
Hidden data
12. Single-threaded and asynchronous
What is the difference between synchronous and asynchronous?
JS based is a single threaded language
Asynchrony does not block code execution
Synchronization blocks code execution
Handwritten Promise loads an image
What are the scenarios where asynchrony is used at the front end?
Single threaded and asynchronous
Application scenarios
The callback hell and promise
JS is a single-threaded language that can only do one thing at a time
Browsers and NodeJS already support JS to start processes, such as Web workers
JS and DOM rendering share the same thread because JS can modify the DOM structure
Encounter wait (network request, scheduled task)
Need the asynchronous
Callback function form
Application Scenarios:
Web requests, such as Ajax image loading
A scheduled task, such as setTimeout
Handwritten Promise loads an image
Promise resolves the callback hell problem
function loadImg(src) {
return new Promise((resolve, reject) = > {
const img = document.createElement('img'Img. onload = () =>{resolve(img)} img. onError =() = > {
reject(new Error())
}
img.src = src
})
}
const url= ' '
const url2 = ' '
loadImg(url).then(img= > {
console.log(img.width)
return img
}).then( img= > {
console.log(img.height)
return loadImg(url2)
}).then(img2= >{
}).catch(err= >{})Copy the code
13. Asynchronous – Advanced
event loop
Please describe the mechanism of event loop.
What are macro tasks and micro tasks, and what is the difference between them?
What are the three states of a Promise? How does it change?
Async/await syntax
Promise and setTimeout execution order?
Plus the order of async/await?
14. Event loop (Event loop/event polling)
JS runs in a single thread
Asynchrony is implemented based on callbacks
The Event loop is how asynchronous callbacks are implemented
How is JS executed?
From front to back, line by line
If a line fails, stop the following code
Execute synchronous code first, and then execute asynchronous code
Event Loop procedure:
Synchronizes code and executes it line by line on the Call Stack
In the case of asynchrony, it ‘records’ and waits for an opportunity (timing, network request, etc.).
When the time is right, move to the Callback Queue
If the Call Stack is empty (that is, the synchronized code is finished) the Event Loop starts working
Search the Callback Queue and move it to the Call Stack if any
And then continue to search (like perpetual motion machines)
- Call Stack: code execution
- Web ApIs: processing timers, asynchronous ApIs
- Callback Queue: Places the timer to be executed or returns the result of the network request
- The Event Loop, polling from the Callback Queue, is executed in the Call Stack
DOM events and Event loops
JS is single threaded
Asynchronous (color map Timeout, Ajax, etc.) uses callbacks, based on event loops
DOM events also use callbacks, based on event loops, but DOM events are not asynchronous
16. promise
Three states
The manifestation and change of state
Effects of then and catch on state
Three states:
pending resolved rejected
Pending – “Resolved” or Rejected
The state is irreversible
Pending state, which does not trigger then and catch
Resolved state, will trigger then
The Rejected state triggers a catch
Then and catch change state
Resolved then Return Rejected when the error message is returned
‘Catch’ returns’ Resolved ‘and’ Rejected ‘when an error is reported
Promise.resolve().then(() = >{
console.log(1)
}).catch(() = >{
console.log(2)
}).then(() = > {
console.log(3)})/ / 1
/ / 3
Copy the code
Promise.resolve().then(() = >{
console.log(1)
throw new error('err');
}).catch(() = >{
console.log(2)
}).then(() = > {
console.log(3)})/ / 1
/ / 2
/ / 3
Copy the code
Promise.resolve().then(() =>{
console.log(1)
throw new error('err');
}).catch(() = >{
console.log(2)
}).catch(() = >{
console.log(3)})/ / 1
/ / 2
` `` `` `javascript
Promise.reject().then(() = >{
console.log(1)
}).catch(() = >{
console.log(2)
}).then(() = > {
console.log(3)})/ / 2
/ / 3
Promise.reject().then(() = >{
console.log(1)
throw new error('err');
}).catch(() = >{
console.log(2)
}).then(() = > {
console.log(3)})/ / 2
/ / 3
Promise.reject().then(() =>{
console.log(1)
throw new error('err');
}).catch(() = >{
console.log(2)
}).catch(() = >{
console.log(3)})/ / 2
Copy the code
(async function() {
console.log('start')
const a = await 100;
console.log('a', a);
const b = await Promise.resolve(200)
console.log('b', b)
const c = await Promise.reject(300) // Do not execute after error
console.log('c', c)
console.log('end')
})()
// start
// a 100
// b 200
Copy the code
17. async/await
Asynchronous callback callback hell
Promise then catch chain calls, but also based on callback functions
Async /await is synchronous syntax for writing asynchronous code that completely eliminates callback functions
18. Relation between async/await and Promise
Async /await is the ultimate weapon against remote callbacks
But Promise and Promise aren’t mutually exclusive. Instead, they complement each other
The async function is executed and returns a Promise
Await as opposed to Promise then
try… Catch catches exceptions instead of the catch of Promise
async function fn() {
return 100
}
(async function() {
const a = fn()
const b = await fn()
console.log(a)
console.log(b)
})()
// Promise { 100 }
/ / 100
Copy the code
The nature of asynchrony
Async /await is the ultimate weapon against asynchronous callbacks
JS is still single threaded, asynchronous, and event loop-based
Async /await is just a syntactic sugar, but this sugar smells good!
async function async1() {
console.log('async1 start') / / 2
await async2()
Callback = async; // await; callback = async
// Similar event loop, setTimeout()
// setTimeout(function() { console.log('async1 end')})
// Promise.then(res => {console.log('async2 end')})
console.log('async1 end') / / 5
}
async function async2() {
console.log('async2') / / 3
}
console.log('start') / / 1
async1()
console.log('end') / / 4
Copy the code
Print:
start
async1 start
async2
end
async1 end
async function async1() {
console.log('async1 start') / / 2
await async2()
// await; the following three lines can be treated as callback
console.log('async1 end') / / 5
await async3()
// await the following line as the contents of the callback
console.log('async1 end2') / / 7
}
async function async2() {
console.log('async2') / / 3
}
async function async3() {
console.log('async3') / / 6
}
console.log('start') / / 1
async1()
console.log('end') / / 4
Copy the code
Print:
start
async1 start
async2
end
async1 end
async3
async1 end2
20. for… Of the use of
for… In (and forEach for) is regular synchronous traversal
for… Of is often used for asynchronous traversal
function muti(num) {
return new Promise(resolve= >{
setTimeout(() = >{
resolve(num*num)
}, 1000)})}const nums = [1.2.3]
nums.forEach(async (i) =>{
const res = await muti(i)
console.log(res)
})
Copy the code
Print 1, 4, 9 in a second
ForEach synchronizes muti and prints one second later
function muti(num) {
return new Promise(resolve= >{
setTimeout(() = >{
resolve(num*num)
}, 1000)})}const nums = [1.2.3]
// nums.forEach(async (i) =>{
// const res = await muti(i)
// console.log(res)
// })! (async function() {
for(let i of nums) {
const res = await muti(i)
console.log(res)
}
})()
/ / 1 4 9
// for of execute the next one
Copy the code
21. Macrotasks and microtasks
What are macro tasks and what are micro tasks
Event loop and DOM rendering
The difference between microtasks and macro tasks
-
Macro tasks: setTimeout, setInterval, Ajax, DOM events
-
Microtasks: Promise async/await
Microtasks are executed earlier than macro tasks
console.log(100)
setTimeout(() = >{
console.log(200)})Promise.resolve().then(res= >{
console.log(300)})console.log(400)
// 100 400 300 200
Copy the code
Event loop and DOM rendering
JS is single threaded and shares a thread with DOM rendering
When JS executes, leave some time for DOM rendering
Call Each time the Stack is cleared (that is, each poll result), that is, the synchronization task is complete
Both are opportunities to re-render the DOM, and re-render if the DOM structure changes
Then the next Event Loop is triggered
Macro task: triggered after DOM rendering, such as setTimout
Microtasks: Trigger before DOM rendering, as Promise
<div id="content"></div>
<script>
let p = document.createElement('p');
p.innerHTML = 'I'm p tag';
document.getElementById('content').append(p);
// Macro task: after DOM rendering
setTimeout(() = >{
console.log('length'.document.getElementById('content').children.length); / / 1
alert('setTimeout'); // Is DOM rendered --yes
})
// Microtasks: before DOM rendering
Promise.resolve().then(() = >{
console.log('length'.document.getElementById('content').children.length); / / 1
alert('Promise then'); // Is DOM rendered? ---No
})
</script>
Copy the code
Why are microtasks performed earlier
Microtasks are mandated by ES6 syntax
Macro tasks are specified by the browser
Micro Task Queue Micro task queue
Callback Queue Specifies the macro task queue
async function async1() {
console.log('async1 start') / / 2
await async2()
// await as callback content -- microtasks
console.log('async2 end') / / 6
}
async function async2() {
console.log('async2') / / 3
}
console.log('script start') / / 1
setTimeout(() = >{ // Macro task setTimeout
console.log('setTimeout') / / 8
}, 0)
async1()
// When a promise is initialized, the function passed in is executed immediately
new Promise(function(resolve){
console.log('promise1') / / 4
resolve()
}).then(function() { Micro / / task
console.log('promise2') / / 7
})
console.log('script end') / / 5
// The event loop --call stack is cleared.
// Perform microtasks
// Try to trigger DOM rendering
// Trigger event loop to execute macro task
Copy the code
22. Describe the Event loop mechanism (graphable)
23. From JS basics to JS Web APIS
Basic JS knowledge, specified syntax (ECMA 261 standard)
JS Web API, API for Web manipulation (WC standard) – add DOM elements, text, set CSS styles, listen for events, get browser information
The former is the basis of the latter, the combination of the two can be really practical application
JS Basic knowledge:
The type and calculation of variables
Prototype and prototype chain
Scope and closure
JS Web API:
DOM manipulation
BOM Operation Operations on the browser
event
ajax
storage
24. Storage:
cookie
localStorage
sessionStorage
Cookies:
It is used for browser and server communication
Is borrowed to local storage
This can be modified by document.cookie =”
Disadvantages:
The maximum storage size is 4kb
HTTP requests must be sent to the server to increase the amount of requested data
It can only be stored with document.cookie=”
LocalStorage and sessionStorage:
Html5 is specifically designed for storage and can hold up to 5M
API simple setTtem,getItem
Will not be sent out with the HTTP request
LocalStorage:
Data is stored permanently unless code or code is deleted
SessionStorage:
Data only operates on the current session and is requested when the browser is closed
Generally use localStorage will be more
25. DOM
The Vue and React frameworks are widely used and encapsulate DOM operations
But DOM manipulation has always been a basic, must-have knowledge for front-end engineers
Front-end programmers who only know VUE and don’t understand DOM manipulation won’t last long
What kind of data structure is DOM
Common apis for DOM manipulation
Attr and property
Insert multiple DOM nodes at once for performance reasons
Nature of the DOM
DOM node operation
DOM structure manipulation
DOM performance
26. The nature of the DOM
A tree structure
27. DOM node operations
Get DOM node
attribute
Property: Modifies the attributes of an object, which are not reflected in the HTML structure
Attribute: Modifying AN HTML attribute changes the HTML structure
Both have the potential to cause DOM re-rendering
const div = document.getElementById('content')
// property
div.style.color = ' '
// attribute
div.getAttribute('index')
div.setAttribute('index'.'1')
Copy the code
A node is added or inserted
Gets the list of child elements, gets the parent element
Deleting child elements
const div = document.getElementById('content')
const div2 = document.getElementById('content2')
const p = document.createElement('p')
// Insert the label
div.appendChild(p)
// Move the label
div2.appendChild(p) // move p under div to div2
// Get the parent node
p.parentNode
// Get the child element
div2.childNodes // Include text nodes need to be screened out
div2.childNodes
Array.prototype.slice.call(div2.childNodes).filter(child= >{
return child.nodeType === 1 // Label node
// nodeType === 3 // text node
})
Copy the code
28. DOM performance
DOM manipulation is’ expensive ‘, so avoid frequent DOM manipulation
Cache DOM queries
Change the frequent operation to a one-time operation
// DOM query results are not cached
for (let i = 0; i < document.getElementsByTagName('p').length; i++){
// For each loop, length is computed and DOM queries are performed frequently
}
// Cache DOM query results
const pList = document.getElementsByTagName('p');
const length = pList.length
for( let i =0; i < length; i++){// Cache length, only one DOM query
}
Copy the code
// Frequent operation is changed to one-time operation
const listNode = document.getElementById('list')
// Create a document fragment that has not yet been inserted into the DOM tree
const frag = document.createDocumentFragment()
// Perform the insert
for(let x = 0; x<10; x++){const li = document.createElement('li');
li.innerHTML = 'list item' + x;
frag.appendChild(li)
}
listNode.appendChild(frag)
Copy the code
29. The BOM
Identify the browser type
navigator
screen
location
history
const ua = navigator.useAgent
ua.indexOf('Chrome')
screen.width
loaction.href / / url
loaction.protocal / / agreement
loaction.host / / the port number
location.hostname //
loaction.search
loaction.hash
loaction.pathname
history.back()
hitory.forward()
Copy the code
Events 30.
event
The event bubbling
The event agent
// Event binding
function bindEvent(elem, type, fn) {
elem.addEventListener(type, fn)
}
const a = document.getElementById('a')
bindEvent(a, 'click'.e= > {
e.preventDefault() // Prevent default behavior
alert('clicked')})Copy the code
// Events bubble up
// Event binding
function bindEvent(elem, type, fn) {
elem.addEventListener(type, fn)
}
const a = document.getElementById('a')
bindEvent(a, 'click'.e= > {
e.stopProgation() // Prevent default behavior
alert('clicked')})Copy the code
Event bubbling principle:
Based on DOM tree structure
Events bubble up the trigger element
Application scenario: Proxy
// Event broker
// Events are bound to parent tags, default behavior
const btn = document.getElementById('btn')
bindEvent(btn, 'click'.'a'.function(event) {
event.preventDefault()
alert(this.innerHTML)
})
function bindEvent(elem, type,selector, fn) {
if (fn == null) {
fn = selector
selector = null
}
elem.addEventListener(type, event= >{
const target = event.target
if (selector) {
// Proxy binding
if (target.matchs(selector)) {
fn.call(target, event)
}
} else {
// Plain binding
fn.call(target, event)
}
})
}
Copy the code
31. http
HTTP common status code
Common HTTP headers
Resrful API
HTTP caching mechanism
The HTTP status code
1XX The server receives a request
The request for 2xx is successful, for example, 200
3xx redirection, such as 302
4XX client error, such as 404
5XX server error, such as 500
301 permanent redirect, browser is permanent old address no longer used, direct access to the redirected address returned
302 temporary redirect, browser still accessing the old address
304 The resource is not modified
403 No Permission
504 Gateway times out
methods
Get Get data
Post New data
Patch/PUT Updates data
Delete Delete data
Restful API
Traditional API design: Treat each URL as a function
Restful API design: Treat each URL as a unique resource
Use url parameters as little as possible
Use method to indicate the operation type
Traditional API design: / API /list? pageIndex = 2
Restful API design: / API /list/2
Common HTTP headers
request headers
Accept Specifies the format of the data accepted by the browser
Accept-encoding Specifies the compression algorithm accepted by the browser
Accept_Languange Indicates the language accepted by the browser, such as zh-cn
Connection: keep-alive TCP is used repeatedly
Cookie: automatically carried by the local browser
Host: domain name
User-agent (UA) Indicates the browser information
Content-type Specifies the format of the data to be sent, for example, Application/JSON
response headers:
Content-type: indicates the format of returned data
Content-length: indicates the size of returned data
Content-encoding: Compression algorithm for returned data: flesh gzip
Set-cookie: sets the Cookie
Header User-defined header
Cache-relevant headers
Cache-Control Expires
Last-Modified IF-Modified-Since
Etag If-None_match
32. HTTP cache
HTTP cache strategy (mandatory cache + negotiated cache)
What is caching?
Why cache?
What resources can be cached? – Static resources (JS CSS IMG)
HTTP cache: Mandatory cache
Cache-Control
In the Response Headers
Controls the logic of forced caching
Example: cache-control: max-age = 31536000 (in seconds)
The value of the cache-control:
max-age
no-cache
no-store
private
public
Expires
Be Responese Headers
Also to control cache expiration
Has been replaced by cache-control
HTTP cache – Negotiated cache
Server side caching policy
The server determines whether the client resource is the same as the server resource
If consistent, 304 is returned, otherwise 200 and the latest resource is returned
Resource identifier
In Response Headers, there are two types:
Last-modified Time when the resource was Last Modified
A unique identifier for an Etag resource (a string, similar to a human fingerprint)
Coexistence uses Etag in preference
Last-modified is only accurate to the second
Etag is more accurate if the resource is produced repeatedly with the same content
Three refresh operations:
Normal operation: enter URL in address bar, jump link, forward and backward, etc
Manual Refresh: F5, click refresh button, right click menu refresh
Force refresh: CTRL +F5
Different refresh operations, different cache policies
Normal operation: Force cache valid, negotiate cache valid
Manual refresh: Force cache invalidation and negotiate cache validity
Force refresh: Force cache invalidation, negotiation cache invalidation
33. Development environment
git
A debugging tool
caught
webpack babel
Common Linux Commands
34. git
Git commit -m 'XXX' git push origin master git pull origin Master git branch // checkout the branch git checkout -b XXX // checkout the branch git checkout XXX // checkout the branch git fetch // checkout all branches git merge XXX // merge the branch git fetch Git diff /git diff XXX ---- change the contents git status // check the contents you need to commit git log git stash // Put aside the current contents git stash pop // put aside git show Name XXX git config user.email XXX Create a project HTTPS // Enter the username and password SSH // You need to generate an SSH public keyCopy the code
35. Chrome debugging tool
36. Caught
Mobile terminal page H5, view network requests, need to use tools to capture packets
Windows usually uses Fiddler
Mac OS uses Charles
Cell phones and computers together with a LAN
Proxy the phone to the computer
Mobile phone browsing web, you can capture the bag
Viewing network Requests
Site agent
https
37. Webpack and Babel
ES6 is modular and not supported by browsers
ES6 syntax, not fully supported by browsers
Compress and integrate code to make web pages load faster
38. Linux command
SSH Username@IP Address Enter the password ls // View folders/files ls -a // View all files ll // View the list form clear // Clear mkdir dir // Create a folder rm -rf dir // Delete folders/files CD Dist // / Enter directory.. // go back to the parent directory mv index.html index. HTML // change the file name mv index.html dist/index.html // move to the dist folder touch index.js // create a file vim // Create a new file and open it by pressing esc :w save :q Exit :q! Json // Check the file head package.json // Check the file header grep "Babel" package.json // Check the keywordCopy the code
39. Operating environment
The runtime environment is the browser (server has nodeJS)
Download the web code, render the page, and execute several JS in the process
Ensure that the code is always efficient and stable in the browser
Page loading process
Performance optimization
security
The entire process from entering the URL to rendering the page
Window.onload differs from DOMContentLoaded
The form of loading resources:
The HTML code
Media files, such as pictures, videos, etc
javascript css
The process of loading resources:
DNS resolution: Domain name – IP address
The browser makes an HTTP request to the server based on the IP address (three-way handshake)
The server processes the HTTP request and returns it to the browser
Loads a rendering of the resource
Generate a DOM TREE from HTML code
Generate CSSOM from CSS code
Combine DOM Tree and CSSOM to form Render Tree
Render the page according to the Render Tree
encounter
Until the Render Tree is finished
Why is it recommended to put CSS in head?
After rendering, CSSOM will be found, and the Render Tree will be re-formed. After re-rendering, the sensation will be bad under the condition of network speed card
Put in the head, the benefits, generate DOM Tree and CSSOM integration to form the Render Tree, one time to complete the rendering
Why put suggested JS at the end of the body?
Render Tree Render page, encountered
Load: the page is loaded only after all resources, including images and videos, are loaded
DOMContentLoaded: DOM rendering can be performed, while images and videos may not be loaded
DOMContentLoaded is better than the load
40. Performance optimization
Use memory caching or other methods
Reduces CPU computation and network loading time
Performance optimization for all programming – space for time
How to optimize. Where to start?
Make loading faster:
Reduce resource volume: Compress code
Reduce access times: merge code, SSR server rendering, caching
Use a faster network: CDN
Cache:
Static resources are suffixed with hash to calculate the hash based on the file content
If the file content does not change, the hash and URL will not change
If the URL and file are unchanged, the HTTP caching mechanism is automatically triggered, and 304 is returned
CDN:
SSR:
2. To load web pages with data:
Non-ssr (front and back end separation) : load the page first, then load the data, then render the data
Make rendering faster:
CSS goes under head, JS goes under body
Start executing JS as soon as possible with DOMContentLoadad trigger
Lazy loading (image lazy loading, slide up to load more)
Cache DOM queries
Reduce frequent DOM operations and merge together to insert DOM structures
Throttle and throttle
Stabilization debounce:
function debounce(fn, delay = 500) {
// Timer is in a closure
let timer = null
return function() {
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(() = >{
fn.apply(this.arguments)
timer = null
}, delay)
}
}
Copy the code
Throttling throttle:
Drag events, triggered frequently, tend to stall
function throttle(fn, delay = 500) {
let timer = null
return function() {
if (timer) {
return
}
timer = setTimeout(() = > {
fn.apply(this.arguments)
timer = null
}, delay)
}
}
div.addEventListener('drag', throttle(function(e){
console.log(e)
}))
Copy the code
41. The security
Q: What are the common web front-end attacks?
XSS cross-site request attack:
XSRF cross-site request forgery
XSS attacks:
< script > into a lt. scriptlt; script lt; scriptlt; Will not be attacked as a script
XSS tool, replace
XSRF:
Prevention:
Using the POST interface
Add validation. Like passwords, SMS verification codes, fingerprints
42. Same-origin policy
Origin is the protocol, domain name, and port number
If the protocol, domain name, and port number in an ADDRESS are the same, the IP address belongs to the same source
What is the same origin policy? The same origin policy is a security function of the browser. Client scripts from different sources cannot read or write resources from each other without explicit authorization. So the JS script under a.com uses Ajax to read the file data inside B.com will report an error
Not subject to the same origin policy:
Links, redirects, and form submissions on pages are not restricted by the same origin policy. Cross-domain resource introductions are possible. But JS cannot read or write loaded content.
As embedded in a page<script src="..."></script>.<img>.<link>.<iframe>Etc.Copy the code
43. Cross-domain implementation
www.cnblogs.com/rockmadman/…
44. Polling, long polling, long connection, Websocket
www.cnblogs.com/huchong/p/8…