一.詳解瀏覽器事件捕獲與冒泡
1. 事件委托/事件代理
捕獲階段-->目標(biāo)階段-->冒泡階段
window.addEventListener('click',function(e){
console.log('window捕獲',e.target.nodeName,e.currentTarget.nodeName)
},true)
- 第三個(gè)參數(shù)為true,則監(jiān)聽捕獲事件,不傳或者傳false,則監(jiān)聽冒泡事件
-
e.target
指的是點(diǎn)擊的元素,e.currentTarget
指的是當(dāng)前觸發(fā)事件的元素
2. 阻止事件的傳播
e.stopPropagation()
真正的作用是阻止事件的傳播,既可以阻止事件的捕獲也可以阻止事件的冒泡
面試題:
現(xiàn)在有一個(gè)頁面,這個(gè)頁面上有許多元素,div、p、button等
每個(gè)元素都有自己的click事件,都不相同
現(xiàn)在有一個(gè)新需求,一個(gè)用戶進(jìn)入這個(gè)頁面的時(shí)候,會(huì)有一個(gè)狀態(tài):banned
,我們可以在全局上拿到這個(gè)狀態(tài):window.banned
,
為true
的話表示當(dāng)前用戶被封禁,用戶點(diǎn)擊頁面的任何元素都不執(zhí)行原有邏輯,而是alert
彈窗,提示你被封禁了;
為false
的話表示有操作權(quán)限。
請(qǐng)問:如何實(shí)現(xiàn)?
答:
方案一:在最外層的一個(gè)元素上綁定上一個(gè)捕獲事件,即addEventListener
里的第三個(gè)參數(shù)為true
,如果window.banned
為true
則e.stopPropagation()
。
//const body = document.getElementsByTagName('body')
window.addEventListener('click',function(e){
if(window.banner){
e.stopPropagation()
alert('你被封禁了')
return
}
...
},true)
方案二:window.banner
為true
的時(shí)候展示一個(gè)全屏的最高層級(jí)(即:z-index:99999
)的div遮罩,遮住整個(gè)頁面。
3.阻止默認(rèn)事件
e.preventDefault()
這個(gè)沒啥好說的
4.兼容性問題
addEventListener
--> firefox、Chrome、高版本IE、safari、opera
attachEvent
--> IE7、IE8,除了政府網(wǎng)站,大部分公司不會(huì)再去針對(duì)他們做兼容了
IE瀏覽器里沒有事件捕獲,只有事件冒泡
針對(duì)兼容性做一下封裝
class BomEvent{
constructor(element){
this.element = element
}
addEvent(type,handler){
if(this.element.addEventListener){
this.element.addEventListener(type,handler,false)
} else if (this.element.attachEvent){
this.element.attachEvent(`on${type}`,function(){
// 這是處于ie7或8的一個(gè)環(huán)境,不支持箭頭函數(shù),所以這里做一下綁定
handler.call(element)
})
} else {
this.element[`on${type}`]=handler
}
}
removeEvent(type,handler){
if(this.element.removeEventListener){
this.element.removeEventListener(type,handler,false)
}else if(this.element.detachEvent){
this.element.detachEvent(`on${type}`,handler)
}else{
this.element[`on${type}`] = null
}
}
}
// IE瀏覽器里沒有事件捕獲,只有事件冒泡
function stopPropagation(event){
if(event.stopPropagation){
event.stopPropagation() //標(biāo)準(zhǔn)w3c瀏覽器
}else{
event.cancelBubble = true // IE
}
}
function preventDefault(event){
if(event.preventDefault){
event.preventDefault()
}else{
event.returnValue = false
}
}
二:瀏覽器請(qǐng)求相關(guān)內(nèi)容Ajax與fetch
原生ajax:
const xhr = new XMLHttpRequest()
xhr.open('GET','http://domain/service') //建立連接,并沒有發(fā)送請(qǐng)求
//監(jiān)聽狀態(tài)
xhr.onreadystatechange = function(){
// 表示請(qǐng)求還沒有完成
if(xhr.readyState !== 4){
return
}else if(xhr.status === 200){
// 請(qǐng)求成功
console.log(xhr.responseText)
}else{
//報(bào)錯(cuò)了
console.error(`HTTP error,status=${xhr.status},errorText = ${xhr.statusText}`)
}
}
// 超時(shí)時(shí)間
xhr.timeout = 3000
xhr.ontimeout = ()=>{
console.log('請(qǐng)求超時(shí)')
}
// 上傳進(jìn)度條
xhr.upload.onprogress = p => {
const percent = Math.round((p.loaded / p.total)*100) + '%'
}
xhr.send() //發(fā)送請(qǐng)求
fetch:瀏覽器新增的fetch,內(nèi)部封裝了promise
fetch('http://domain/service',{
method: 'GET',
credentials: 'same-origin' // 同域的請(qǐng)求會(huì)帶上cookie
}).then(response => {
if(response.ok){
//請(qǐng)求成功
return response.json()
}
throw new Error(' http error')
}).then(json => {
console.log(json)
}).catch(error => {
console.error(error)
// 統(tǒng)一的錯(cuò)誤管理
// 接收fetch出現(xiàn)的錯(cuò)誤
// 接收請(qǐng)求錯(cuò)誤信息
})
fetch
不能直接通過catch
來獲取請(qǐng)求錯(cuò)誤信息,而是要通過判斷response.ok
來返回出錯(cuò)誤信息再通過catch
來抓到錯(cuò)誤信息
fetch
自身不支持設(shè)置請(qǐng)求超時(shí),我們自己來封裝一個(gè)
function fetchTimeout(url,init.timeout=3000){
return new Promise((resolve,reject)=>{
fetch(url,init).then(resolve).catch(reject)
setTimeOut(reject,timeout)
})
}
中斷一個(gè)請(qǐng)求
//用于中斷請(qǐng)求
const controller = new AbortController()
fetch('http://domain/service',{
method: 'GET',
credentials: 'same-origin', // 同域的請(qǐng)求會(huì)帶上cookie
signal:controller.sianal
}).then(response => {
if(response.ok){
//請(qǐng)求成功
return response.json()
}
throw new Error(' http error')
}).then(json => {
console.log(json)
}).catch(error => {
console.error(error)
})
controller.abort()//用于中斷請(qǐng)求
請(qǐng)求頭request-header
referer
:表示來源,你是從哪一個(gè)頁面過來這個(gè)頁面的,標(biāo)識(shí)訪問路徑
user-agent
:用來判斷環(huán)境,設(shè)備標(biāo)識(shí)
響應(yīng)頭response-header
access-control-allow-origin
:跨域
用于做域名限制,跨域
access-control-allow-origin:/* ,不做限制
-
content-encoding: 是一個(gè)實(shí)體消息首部,用于對(duì)特定媒體類型的數(shù)據(jù)進(jìn)行壓縮。當(dāng)這個(gè)首部出現(xiàn)的時(shí)候,它的值表示消息主體進(jìn)行了何種方式的內(nèi)容編碼轉(zhuǎn)換。這個(gè)消息首部用來告知客戶端應(yīng)該怎樣解碼才能獲取在
Content-Type
中標(biāo)示的媒體類型內(nèi)容。<pre class="md-fences md-end-block ty-contain-cm modeLoaded" spellcheck="false" lang="js" cid="n20" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-radius: 3px; padding: 8px 4px 6px; margin-bottom: 15px; margin-top: 15px; width: inherit;">Content-Encoding: gzip
Content-Encoding: compress
Content-Encoding: deflate
Content-Encoding: identity
Content-Encoding: br</pre> set-cookie:響應(yīng)首部
Set-Cookie
被用來由服務(wù)器端向客戶端發(fā)送 cookie。
status狀態(tài)碼
響應(yīng)分為五類:信息響應(yīng)(100
–199
),成功響應(yīng)(200
–299
),重定向(300
–399
),客戶端錯(cuò)誤(400
–499
)和服務(wù)器錯(cuò)誤 (500
–599
)。
請(qǐng)求成功。成功的含義取決于HTTP方法:
GET:資源已被提取并在消息正文中傳輸。
HEAD:實(shí)體標(biāo)頭位于消息正文中。
POST:描述動(dòng)作結(jié)果的資源在消息體中傳輸。
TRACE:消息正文包含服務(wù)器收到的請(qǐng)求消息
該請(qǐng)求已成功,并因此創(chuàng)建了一個(gè)新的資源。這通常是在POST請(qǐng)求,或是某些PUT請(qǐng)求之后返回的響應(yīng)。
重定向。
被請(qǐng)求的資源已永久移動(dòng)到新位置,并且將來任何對(duì)此資源的引用都應(yīng)該使用本響應(yīng)返回的若干個(gè) URI 之一。如果可能,擁有鏈接編輯功能的客戶端應(yīng)當(dāng)自動(dòng)把請(qǐng)求的地址修改為從服務(wù)器反饋回來的地址。
臨時(shí)重定向。
請(qǐng)求的資源現(xiàn)在臨時(shí)從不同的 URI 響應(yīng)請(qǐng)求。由于這樣的重定向是臨時(shí)的,客戶端應(yīng)當(dāng)繼續(xù)向原有地址發(fā)送以后的請(qǐng)求。只有在Cache-Control或Expires中進(jìn)行了指定的情況下,這個(gè)響應(yīng)才是可緩存的。
304:協(xié)商緩存,服務(wù)器文件未修改
面試題
vue/react
創(chuàng)建的單頁面應(yīng)用(spa),生成的index.html
如果要做緩存應(yīng)該做什么緩存?
答:協(xié)商緩存