Keep updating ing ~
- Github address of the front-end infrastructure.
README.md
You can download it totypora
(Github’s shortcut to create markdown directory is not practical, so we may try to create a post later, so we will not do relevant processing for the time being) - Front-end base Gitbook address.
README.md
Will update the progress content in real time.gitbookConsider the whole study after finishing finishing, and then go to the unified processing release, please look forward to!gitbook
Version can be recommended later fragmentation time for review. - Front-end basic CSDN address.
CSDN
Blog postFront end self-cultivation advancedIn, will also be a real-time update of the relevant knowledge points. - Front end foundation 1 nuggets address, front end foundation 2 nuggets address
⭐️ is the best encouragement oh wink ~ 💗
JS Web API
- Basic JS knowledge, specified syntax (ECMA 262 standard)
- JS WEB API, WEB manipulation API (W3C standard)
- The former is the foundation of the latter, and the combination of the two can be really applied in practice
JS WEB API scope
- DOM manipulation
- BOM operations (browser things: browser navigation, browser URL, browser jump, browser width and height)
- event
- ajax
- storage
preface
- The Vue and React frameworks are widely used and encapsulate DOM operations
- But DOM manipulation has always been a basic prerequisite for front-end engineers
- Programmers who can only framework but not DOM manipulation won’t last long
5.17
1, DOM operation (Document Object Model)
The title
-
Which data structure DOM belongs to
- Based on tree structure
-
Common apis for DOM manipulation
-
The difference between attR and property
- Property: Changes the properties of an object, not reflected in the HTML structure (does not affect the node)
- Attr: Directly modify the HTML attribute, will change the HTML structure (change the tag structure)
- Both can cause DOM re-rendering (try to do this with property, because setting property will definitely re-render, not attribute. Re-dom rendering is a performance-intensive affair.)
-
Insert multiple DOM nodes at once for performance reasons
- Dom node cache
- Create a fragment and insert createFragment once
knowledge
- Nature of the DOM
- A tree parsed from HTML
HTML is actually a special kind of XML
-
DOM node operations
- Access to the node
- getElementById
- getElementByClassName
- getElementByTagName
- document.querySelectorAll
- Attribute: Directly modifies the DOM structure, which directly affects the tag
const pList = ducument.querySelectorAll('p') const p = pList[0] p.getAttribute('data-name') p.setAttribute('data-name','smileyqp') p.getAttribute('style') p.setAttribute('style','font-size:30px') Copy the code
- Property: Modify the properties of a js variable. Setting this does not affect the tag
- A form of manipulation with js properties
const pList = ducument.querySelectorAll('p') const p = pList[0] console.log(p.style) console.log(p.style.width) Console. log(p.style.classname) console.log(p.nodename) //nodeName nodeName console.log(p.nodetype) //nodeType nodeTypeCopy the code
- Access to the node
-
Manipulation of DOM structures
- Add/insert operations
- Gets the list of child elements, gets the parent element
- Deleting child Nodes
Const div1 = document.getelementById ('div1') const div2 = document.getelementById ('div2') // New node const newP = CreateElement ('newP') newp.innerhtml = 'this is newP' // insert div1.appendChild(newP) // insert div2.appendChild(p1) // Get the parent element console.log(p1.parentNode) // get the list of child elements; Class seems to be set into an Array of Array. Prototype. Slice. Call, then filter type is 1, the p element node div1..childnodes (); const div1childNodesP = Array.prototype.slice.call(div1.childNodes()).filter((child)=>{ if(child.nodeType === 1){ return true; }} div1.removechild (div1childNodesP[0])Copy the code
-
DOM performance
- Dom queries are cached (reduce DOM queries). Change dom cache, DOM query to variable query)
For (let I = 0; i<document.getElementByTagName('p').length; I++){// each query recalculates the length, Frequently for dom querying} / / cache the results of the query dom const plist = document. The getElementByTagName (' p ') const plength = plist. Length; for(let i = 0; i<plength; I++){// cache dom query, only need to do one dom query}Copy the code
- Change a frequent operation to a single operation
- Create a file fragment and insert it again (createFragment)
Const listNode = document. GetElementById (' list ') / / create a document fragment, at this time has not yet been inserted into the dom const frag = document. CreateDocumentFragent (); // insert for(let x = 0; < = 10; x++){ const li = document.createElement('li'); i.innerHTML = 'list item'+x; Listnode.appendchild (frag)} // Insert into the dom tree.Copy the code
2. BOM Operation (Browser Object Model)
- How do I identify browser types
- Analyze and disassemble parts of the URL
knowledge
- Navigator: Browser information
- Screen: indicates screen information
- Location: indicates the address information
- History: indicates forward and backward information
The navigator and screen
//navigator const ua = navigator.userAgent; // Screen onsole.log(screen.width) const isChrome = ua.indexof ('Chrome') console.log(isChrome) //screen onsole.log(screen.width) cobsole.log(screen.height)Copy the code
The location and history
//location console.log(location.href) console.log(location.protocol) console.log(location.pathname) Console.log (location.search) // get the argument passed to the URL console.log(location.hash) // Get the hash that follows # //history history.back(); history.forward()Copy the code
3, events,
Topic:
- Write a generic event listener function
- Describes the flow of event bubbling
- Based on dom tree structure
- Events bubble up the trigger element
- Application scenario: Event proxy
- Infinite drop-down list of images, how to listen to each click of the image
- The event agent
- through
e.target
To get the trigger element - Matches is used to determine whether the element fires
knowledge
- Event binding (addEventListener)
const btn = document.getElementById('btn1')
btn.addEventListener('click',event=>{
console.log('click')
})
Copy the code
// Common binding: a simple generic event binding function; Function bindEvent(elem,type,fn){elem. AddEventListener (type,fn)} const a = document.getElementById('link1') bindEvent(a,'click',e=>{ e.preventDefault(); // Prevent default behavior; For example, organize links by clicking the jump console.log(e.target); // Get clicked element alert('this is aaa')})Copy the code
- Event bubbles: Bubbles up and up the DOM structure
- For example, if you add an event to the body, if you click on its child element, it will bubble up to the body
stopPropagation
It stops bubbles
- The event agent
- Event broker: If you don’t want to bind events one by one, bind events to its parent tag.
- Event brokering is based on event bubbling, and only with event bubbling mechanism can the brokering be implemented on this mechanism.
- Event broker scenarios: Usually through some form of loading, such as an infinite drop-down list of images. It may not be possible to know how many image tags there are in the container, nor to bind events to each one. At this point we can get the event by bubbling, and we can get the clicked image in some way
Event binding functions (consider proxies)
- Combine the two (plus bubbling)
Function bindEvent(elem,type,selector,fn){if(fn == null){function bindEvent(elem,type,selector,fn){ So knowledge common binding, the third argument is fn fn = selector; selector = null; } elem.addEventListener(type,event=>{ //event.preventDefault(); const target = event.target; If (target. Matches (selector)){if(target. Call (target,event)){ }else{// No selector, normal binding case fn.call(target,event) // Because fn's this needs to refer to this element, Const div3 = document.getelementById ('div3') BindEvent (div3,'click','a',function(event){// alert(this.innerHTML) })Copy the code
5.18
4, ajax
The title
- Write a simple Ajax by hand
function ajax(url){ const p = new Promise((resolve,reject)=>{ const xhr = new XMLHttpRequest(); xhr.open('GET','data/test.json',true); Xhr.onreadystatechange = function(){if(xhr.readyState === 4){if(xhr.status === 200){if(xhr.status === 200){ resolve(JSON.parse(xhr.responseText)) }else if(xhr.status === 404){ reject(new Error('404 not found! '))}}}}); xhr.send(null) return p; } const url = '/data/test.json' ajax(url).then(res=>{ console.log(res) }).catch(err=>{ console.log(err) })Copy the code
- Common implementations across domains
knowledge
- XMLHttpRequest
// Write simple Ajax //get request; Const XHR = new XMLHttpRequest(); xhr.open('GET','data/test.json',true); Xhr.onreadystatechange = function(){if(xhr.readyState === 4){if(xhr.status === 200){if(xhr.status === 200){ alert(xhr.responseText) }else if(xhr.status === 404){ console.log('404 not found ') } } } xhr.send(null)Copy the code
- Status code
- Cross-domain: Same-origin policy cross-domain solution
- What is Cross-domain (Same Origin Policy)
- JSONP
- CORS (Server support)
The same-origin policy
-
When making an Ajax request, the browser requires that the current web page and the server must be of the same origin (security)
-
Cognate: The protocol, domain name, and port must be consistent
-
Loading images, CSS, and JS can ignore the same origin policy
<img src=""/>
(Note: some pictures may be anti-theft)<link src=""/>
<script src=""></script>
<img src=""/>
Can do statistics, can use the third party statistics service<link src=""/>
and<script src=""></script>
You can use a CDN, which is usually an outfield<script src=""></script>
JSONP can be implemented
Cross domain
- All cross-domains must be allowed and coordinated by the serve end
- Without the permission of the serve end to achieve cross-domain, indicating that the browser has vulnerabilities, danger signal
JSONP
<script></script>
Cross-domain restrictions can be bypassed- The server can dynamically concatenate data back at will
- So,
<script></script>
Cross-domain data can be obtained if the server is willing to return it
The CORS server sets the HTTP header
- Servers are allowed to cross domains
Common ajax plug-ins
- jquery
- fetch
- axios
5, storage,
The title
- Describes the differences between cookie, localStorage, and sessionStorage
- capacity
- API for ease of use
- Whether to follow the HTTP request
knowledge
- cookie
- Localstorage and sessionstorage
cookie
- It is used for browser and server communication
- Is “borrowed” for local storage
- available
document.cookie=...
To modify the - The maximum storage size is 4kb
- HTTP requests need to be sent to the server to increase the amount of request data
- Can only use
Document. The cookie =...
To revise it. It’s too crude
Localstorage and sessionstorage
- Html5 is specifically designed for storage and can store up to 5M
- API simple and easy to use, using setItem and getItem
- Does not go out with HTTP requests
Localstorage is different from SessionStorage
- Localstorage data is permanently stored unless deleted by code or manually
- Sessionstorage will only exist when the current session browser is closed and empty
- Generally use localstorage more
6. Development environment
- git
- A debugging tool
- caught
- webpack babel
- Common Linux Commands
git
- The most commonly used code versioning tool
- Git must be used for large projects with multiple collaborators
Chrome Debugger
- elements
- console
- debugger
- network
- application
caught
- Mobile terminal page H5, view network requests
- Win usually uses Fiddler
- Charles is used for MAC
- Packet capture process:
- Cell phone computer with a LAN
- The phone goes to the computer
- Mobile phone browsing web can capture the bag
- View url request
- Site agent
- https
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
linux
- Companies typically launch on Linux servers
- The test machine is the same, Linux
- Linux Basic Commands
Operating Environment
- The runtime environment is the browser (with nodeJS on the server)
- Download the web code, render the page, and execute several jS in the process
- Make sure it’s stable and efficient in the browser
The runtime environment involves front-end content
- Page loading process
- Performance optimization (Experience optimization)
- security
Page loading and rendering process
The title
- The entire process from entering the URL to rendering the page (see below: resource form, loading process, rendering process)
- Downloading resources: Each resource type and downloading process
- Render pages: combine HTML, CSS, JS images, etc
window.onload
andDOMContentLoad
The difference between- The window.onload page is fully loaded including images
- DOMContentLoaded is used to render the DOM before the images and videos are loaded
document.addEventListener('load',()=>{
console.log('window loaded')
})
document.addEventListener('DOMContentLoaded',()=>{
console.log('dom loaded')
})
Copy the code
knowledge
- The form of the loaded resource
- The process of loading resources
- The process of rendering a page
Resources form
- The HTML code
- Media files, such as pictures and videos
- Js, CSS code
The loading process
- DNS resolution: Domain name =>IP address
- The browser sends an HTTP request to the server using an IP address
- The server processes the HTTP request and returns it to the browser
Rendering process
- Generate a DOM tree from HTML
- Generate CSSOM from CSS (CSS object Model)
- Combine THE DOM tree with csSOM to form a Render tree (like a DOM tree with CSS properties hanging from it)
- Render the page according to the Render Tree
- encounter
<script>
Then suspend rendering, load and execute js code first, and then continue (the JS process and renderer process share one thread). Script may have code that changed the result of previous execution, so it pauses rendering when it encounters script.
Why is it recommended to put CSS in head?
- Prevent repeated rendering (the default style is rendered without CSS, and then the csSOM regenerates the Render Tree and rerenders it. And when the network speed is slow, there may be two style switches for the user.
Why is script recommended for last?
- Not putting js at the end will result in a longer page rendering process. Because JS will pause rendering. We expect to render first and then modify
Image rendering
- Image rendering does not block DOM rendering, but may be left empty until the image is loaded
8. Performance optimization
Performance optimization principles
- Use memory, caching, or other methods
- Reduces CPU computation and network loading time
- (Applicable to all programming performance optimization, space for time)
What to start with
- Load faster
- Reduce resource volume: compress code
- Reduce access times: merge code (JS, CSS, Sprite), SSR server rendering (data together to the front end), cache
- Use faster network: CDN (static file access service by region)
- Render faster
- CSS goes in the head, js goes at the bottom of the body
- Execute js as soon as possible and use DOMContentLoad to trigger it
- Lazy loading (image lazy loading, slide-up loading more)
- Cache DOM queries
- Frequent DOM operations are merged into insertions without structure
- Throttle and debounce (render smoother)
The sample
- Resources combined
- The cache
- Static resources are suffixed with a hash hash based on the contents of the file
- If the file content remains the same, the hash remains the same, so the URL remains the same
- The url and file are unchanged, and the HTTP caching mechanism is automatically triggered to return 304 (reducing resource requests)
! [image-20210518173205903](/Users/yqp/Library/Application Support/typora-user-images/image-20210518173205903.png)
-
SSR (Server side render)
- Server-side rendering: Load and render pages and data together
- Non-ssr (front and back end separation) : load web page first, then load data, then render data
- Earlier JSP, PHP, APS were all SSR, now React vue SSR
-
Lazy loading
- Caching DOM queries
- Multiple DOM operations are combined to insert dom structures
- Start JS execution as early as possible
- You can start js execution after dom rendering is complete. You don’t need to wait until images, videos, and other multimedia resources are loaded
5.19
9, function throttling & anti shake
- Function throttling: after a function is executed once, it is executed twice only after the execution period is longer (only the first time is triggered within the specified time).
//fn: the function to intercept; Function throttle(fn,delay){var lastTime = 0; return function(){ var curTime = Date.now(); if(curTime-lastTime>delay){ fn.call(this); LastTime = curTime; LastTime}}}Copy the code
- Anti – shake function: frequently triggered function, within a specified time, only triggered the last time
function debounce(fn,delay){ var timer = null; Return function(){if(timer){clearTimeout(timer)} timer = setTimeout(function(){fn.apply(this) },delay) } }Copy the code
Stabilization debounce
- Scenario: The change event is triggered after listening for text changes in an input box
- Using the keyUp event directly frequently triggers the change event
- Stabilization: The change event is triggered until user input ends or pauses
Function debounce(fn,delay=500){function debounce(fn,delay=500){var timer = null; return function(){ if (timer){clearTimeout(timer); } timer = setTimeout(function(){ fn.apply(this,arguments); timer = null; },delay)} // Use input1.addEventListener('keyup',debounce(function(){console.log(' use anti-shock function: '+this.value)}),1000)Copy the code
Throttling throttle
- Scenario: When you drag an element, always get the element’s position
- If the drag event is used directly, it will trigger frequently, which can easily lead to stagnation
- Keep one frequency firing continuously
function throttle(fn,delay=500){ let timer = null; return function(){ if(timer){return; } setTimeout(()=>{ fn.apply(this,arguments); //apply: bind this, bind timer = null; Div1.addeventlistener (throttle(function(e){console.log(e.offsetx) console.log(e.offty)},100))Copy the code
10, safety
Question: What are the common web front-end attacks
- XSS cross-site request attack
- XSRF cross-site request forgery
XSS cross-site request attack
- Blog front-end interface embedded script script
- Script content: Get cookies and send them to the server (server coordination across domains)
- Publish a blog, someone to view, you can easily get the viewer’s cookie information
XSS prevention
- Replaces special characters. Such as:
<
become&It
;>
become>
Then script will not be executed as a script - You can use
https://www.npmjs.com/package/xss
XSS tool
XSRF cross-site request forgery (similar to phishing links)
- For example, an attacker wants to purchase an item and knows the requested URL to purchase
- Then, in the form of an email, send a link to hide the image
<img src='xxx.com/pay?id=100'/>
. Images can cross domains. - If the recipient has logged in this shopping website, the recipient clicks on the link to open it, then the user information will be brought over, and the user information of the person who clicks on the link will be sent to purchase
XSRF prevention
-
The POST interface is used, because the cross-domain POST interface needs to be supported by the server
-
Add authentication, such as password verification code and fingerprint