Knowledge combing
- BOM operation
- DOM manipulation
- event
- Ajax
- storage
BOM
BOM (Browser object Model) is the setting and retrieval of information about the browser itself, such as the width and height of the browser, and which address the browser should jump to.
- navigator
- screen
- location
- history
Code examples of common functions get browser features (commonly known as UA) and then identify the client, such as Chrome
Var ua = navigator.userAgent var isChrome = ua.indexof ('Chrome') console.log(isChrome) // Get the width and height of the screen Console. log(screen.width) console.log(screen.height) // Get url, protocol, path, parameters, hash etc. Console. log(location.href) console.log(location.protocol) // https: console.log(location.pathname) // /timeline/frontend console.log(location.search) // ? A =10&b=10 console.log(location.hash) // #some //Copy the code
DOM
The server sends the HTML to the browser, and the browser needs to turn the HTML into a DOM to recognize it. HTML is a tree, and DOM is a tree. To understand DOM, we can temporarily put aside the internal factors of the browser and start from JS. That is, DOM can be considered as an HTML structure that JS can recognize, a common JS object or array.
Get DOM node
Var div1 = document.getelementById ('div1') var divList = tagName Document. GetElementsByTagName (' div ') / / set the console log (divList. Length) console. The log (divList [0]) / / var by class ContainerList = document. GetElementsByClassName (' container ') / / / set/get var pList = through CSS selectors Document. QuerySelectorAll (' p ') / / collectionCopy the code
property
A DOM node is a JS object, which conforms to the extensibility properties of objects described earlier
Are JS category attributes, in line with JS syntax standards.
attribute
Attributes are attributes that change HTML directly
Get and set attributes also trigger DOM queries, redrawing, and reordering. Frequent operations affect page performance
The DOM tree operations
Var p1 = document.createElement('p') p1.innerHTML = 'this is AppendChild (p1) // Add the newly created element // move the existing node. Notice, this is move, Var p2 = document.getelementById ('p2') div1.appendChild(p2) var div1 = document.getelementById ('div1') Var parent = div1.parentelement var div1 = document.getelementById ('div1') var Child = div1.childNodes // Delete the node var div1 = document.getElementById('div1') var child = div1.childNodes div1.removeChild(child[0])Copy the code
The event
var btn = document.getElementById('btn1') btn.addEventListener('click', Function (event) {// event.preventdefault () // preventDefault behavior // event.stoppropagation () // prevent bubbling.log ('clicked')})Copy the code
Function bindEvent(elem, type, fn) {elem. AddEventListener (type, fn); Var a = document.getelementById ('link1'); Function (e) {e.preventDefault() // Alert ('clicked')})Copy the code
The bubbling
The < body > < div id = "div1" > < p id = "p1" > activation < / p > < p id = "p2" > cancel < / p > < p id = "p3" > cancel < / p > < p id = "p4" > cancel < / p > < / div > < div id = "div2" > < p Id = "p5" > cancel < / p > < p id = "p6" > cancel < / p > < / div > < / body > / / request click p1 when enter the activated state, Var body = document.body bindEvent(body, 'click', function (e) {// All p clicks bubble up to the body, Because the body is the parent node of P in the DOM structure, Var p1 = document.getelementById ('p1') bindEvent(p1, 'click', Function (e) {e.topPropagation ()})Copy the code
The event agent
< div id = "div1" > < a href = "#" > a1 < / a > < a href = "#" > a2 < / a > < a href = "#" > a3 < / a > < a href = "#" > a4 < / a > < / div > < button > click add an a Tag </button> Event agent: Function bindEvent(div1, 'click', 'a', function () {} function bindEvent(div1, 'click', 'a', function () {} }) and bindEvent(div1, 'click', function () {... }) if (fn == null) {fn = selector selector = null} // bind event elem. AddEventListener (type, Function (e) {var target if (selector) {var target if (selector) { If (target. Matches (selector)) {fn. Call (target, matched); E)}} else {// do not need the event proxy fn(e)}})} Var div1 = document.getElementById('div1') var div1 = document.getElementById('div1') function (e) { console.log(this.innerHTML) })Copy the code
Ajax
XMLHttpRequest
// write XMLHttpRequest var XHR = new XMLHttpRequest() xhr.onreadyStatechange = function () { If (xhr.readyState == 4) {if (xhr.status == 200) {alert(xhr.responsetext)}} xhr.open("GET", "/ API ", false) xhr.send(null) // Status code Description Xhr.readyState status code description: 0 - The proxy is created, but the open() method has not been called. The 1-open () method has been called. The 2-send () method has been called and the header and state are available. 3 - In download, the responseText property already contains some data. Xhr. status indicates the HTTP status code, including 2xx, 3XX, 4xx, and 5XX. The commonly used ones are as follows: 200 Normal 3xx 301 Permanent redirection. A GET request at http://xxx.com (with no/at the end) will be temporarily redirected from 301 to http://xxx.com/ (with/at the end) 302. A temporary, not permanent 304 resource found but does not meet the request criteria will not return any principals. If the head contains if-modified-since: XXX, 304 will be returned If the resource has not been updated. 404 The resource cannot be foundCopy the code
Fetch API
Fetch (), the global function method provided by Fetch, makes it easy to make an asynchronous request and supports the Promise callback.
Fetch ('some/ API /data.json', {method:'POST', // request type GET, POST headers:{}, Of the form Headers object or ByteString body:{}, Blob, BufferSource, FormData, URLSearchParams (get or head cannot contain body) mode: "", // request mode, whether cross-domain, etc. Omit information such as cors, no-cors, or same-origin credentials: ", // cross-domain policies such as omit, same-origin, or include cache: ", // Requested cache mode: Default, no-store, reload, no-cache, force-cache or only-if-cached}). Then (function(response) {... }); Fetch supports the definition of headers. By customizing headers, you can easily implement multiple request methods (PUT, GET, POST, etc.), request headers (including cross-domain), and cache policies. In addition to supporting multiple types of response,Copy the code
Cross domain
Where is the URL different that counts as cross domain? <script SRC =" XXX ">, <img SRC =" XXXX "/>, <link href=" XXXX ">, The SRC /href of these three tags can load resources from other domains, regardless of the same origin policy.Copy the code
-
Resolve cross-domain – JSONP
-
Resolve cross-domain-server setting of HTTP headers
response.setHeader("Access-Control-Allow-Origin", "http://m.juejin.com/"); *" response.setHeader(" access-Control-allow-headers ", "x-requested-with ") is not recommended. response.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS"); Responsetheader (" access-Control-allow-credentials ", "true");Copy the code
storage
- cookie
Cookies themselves are not intended for server-side storage (there are plenty of examples of this in the computer world, such as float in CSS). They are designed to pass information between the server and the client, so we carry cookies with us on every HTTP request. But cookies also have browser-side storage capabilities (such as remembering user names and passwords) and are therefore used by developers. The storage capacity is too small, only 4KB, all HTTP requests are carried, which affects the efficiency of obtaining resources. The API is simple and requires encapsulation to useCopy the code
- LocalStorage and sessionStorage
For localstorage. setItem, try to include a try-catch when using it. Some browsers disable this API