1. 瀏覽器事件模型
- 事件的捕獲和冒泡
- addEventListener & removeEventListener
- 兼容IE7 8 attachEvent
- 事件代理/事件委托
事件代理/事件委托
將孩子的事件監(jiān)聽委托給父親荷鼠,優(yōu)化同類型監(jiān)聽綁定帶來的大量內(nèi)存消耗
// 每一個子節(jié)點單獨綁定
const liList = document.querySelectorAll('li')
for (let i = 0; i < liList.length; i++) {
liList[i].addEventListener('click', (e) => {
alert(i + '' + liList[i].innerHtml)
})
}
// 委托父親節(jié)點來綁定事件
const ul = document.querySelector('ul')
ul.addEventListener('click', (e) => {
const liList = document.querySelectorAll('li')
const index = Array.prototype.indexOf.call(liList, e.target)
if (index >= 0) {
alert(`${index}, ${e.target.innerHTML}`)
}
})
2. 瀏覽器請求相關(guān)
2.1 XML 請求
const xhr = new XMLHttpRequest()
xhr.open('GET', 'https://baidu.com')
xhr.onreadystatechange = () => {
if (xhr.readyState !== 4) {
return
}
if (xhr.state === 200) {
console.log(xhr.responseText)
} else {
console.log('HTTP error', xhr.status, xhr.statusText)
}
}
// xhr.timeout = 1000
// xhr.ontimeout = () => {
// console.log(xhr.responseURL)
// }
// xhr.upload.onprogress = p => {
// console.log (Math.round((p.loaded / p.total) * 100) + '%')
// }
xhr.send()
2.2 fetch
使用 promise 來實現(xiàn) timeout,統(tǒng)一的狀態(tài)管理十分好用
fetch('https://domain/service', {
method: 'GET',
credentials: 'same-origin'
}).then(response => {
if (response.ok) {
return response.json()
}
throw new Error('http error')
}).then(json => {
console.log(json)
}).catch(e => {
console.log(e)
})
function fetchTimeout (url, opts, timeout) {
return new Promise((resolve, reject) => {
fetch(url, opts).then(resolve).catch(reject)
// 時間到了執(zhí)行 resolve, 后面 fetch 就算執(zhí)行到 resolve 也不會扭轉(zhuǎn)狀態(tài)了
setTimeout(reject, timeout)
})
}
中止 fetch凄贩,AbortController
與 fetch 搭配使用
AbortController 接口表示一個控制器對象晌柬,允許你根據(jù)需要中止一個或多個 Web 請求
const controller = new AbortController()
fetch('http://domain/service', {
method: 'GET',
signal: controller.signal
})
.then(res => res.json)
.then(json => console.log(json))
.catch(error => console.log(error))
controller.abort()
2.3 ajax
手寫 ajax
interface IOptions {
url: string;
method: 'GET' | 'POST';
timeout?: number;
data?: any;
}
function objToQuery (obj: Record<string, any>) {
const arr = []
for (let key in obj) {
arr.push(`${key}=${encodeURIComponent(obj[key])}`)
}
return arr.join('&')
}
function ajax (options: IOptions = {
url: '',
method: 'GET'
}) {
return new Promise((resolve, reject) => {
let xhr
let timer
if ((window as any).XMLHttpRequest) {
xhr = new XMLHttpRequest()
} else {
xhr = new ActiveXObject('Microsoft.XMLHTTP')
}
xhr.onreadystatechange = () => {
if (xhr.readState === 4) {
if (xhr.state >= 200 && xhr.state < 300 || xhr.state === 304) {
resolve(xhr.responseText)
} else {
reject(xhr.state + ' ' + xhr.stateText)
}
clearTimeout(timer)
}
}
if (options.method.toUpperCase() === 'GET') {
xhr.open('GET', options.url + '?' + objToQuery(options.data), true)
xhr.send()
} else if (options.method.toUpperCase() === 'POST') {
xhr.open('POST', options.url, true)
xhr.setRequestHeader('ContentType', 'application/x-www-form-urlencoded')
xhr.send(options.data)
}
if (options.timeout) {
timer = setTimeout(() => {
reject('http timeout')
xhr.abort()
}, options.timeout);
}
})
}
2.4 請求頭
2.4.1 cookie
為什么常見的 CDN 域名和業(yè)務(wù)域名不一樣?
// www.baidu.com 業(yè)務(wù)域名
// cdn.aa-baidu.com cdn 域名
為了不攜帶 cookie
- 安全問題。公司不想把攜帶用戶信息的 cookie 給到三方廠商
- cdn 本意為了加速靜態(tài)文件的加載烦秩,與用戶態(tài)無關(guān)狞贱,本不需要 cookie刻获,所以不攜帶 cookie 可以減少請求頭的體積。
- 避免靜態(tài)資源加載阻塞了服務(wù)端請求瞎嬉。HTTP 1.1 / 1.0 同源請求并發(fā)限制 chrome蝎毡、IE、Safari 為 6
2.4.2 referer 來源
2.4.3 user-agent 判斷 webview
User-Agent 首部包含了一個特征字符串氧枣,用來讓網(wǎng)絡(luò)協(xié)議的對端來識別發(fā)起請求的用戶代理軟件的應(yīng)用類型沐兵、操作系統(tǒng)、軟件開發(fā)商以及版本號便监。
2.5 響應(yīng)頭
access-control-allow-origin: *
content-encoding: gzip
set-cookie
2.6 status
200 success
201 created 用于 POST 請求成功
301 永久重定向
302 臨時重定向
304 協(xié)商緩存扎谎,服務(wù)器文件未修改
last-modified: 文件最后一次修改時間
etag: 計算 hash 來判斷文件是否修改
強緩存
Cache-Control: max-age=1000 秒
expires 過期時間 (客戶端時間和服務(wù)端時間可能有偏差)
優(yōu)先級
Cache-Control > expires > Etag > Last-Modified