[JQuery] 替換 document ready 的方法

研究 readyState ,並替換 jQuery $(document).ready 的方法

研究 readyState ,以原生 javascript 的方式去實現!

onreadystatechange
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
console.log(document.readyState);

//監聽,當readystate狀態改變就觸發(loading,interactive,complete)
document.onreadystatechange = function () {

console.log(document.readyState);

if (document.readyState == "loading") {
//這邊一定不會進來,因為網頁一開始狀態就是loading,沒有改變,也不會觸發onreadystatechange
console.log('The document is still loading.');
}
if (document.readyState == "interactive") {
console.log('The document has finished loading and the document has been parsed but sub-resources such as images, stylesheets and frames are still loading.');
}
if (document.readyState == "complete") {
// document is ready. Do your stuff here
console.log('The document and all sub-resources have finished loading. The state indicates that the load event is about to fire.');
}
}

最後使用監聽 DOMContentLoaded 事件

這個事件會是在 document.readyState 是 interactive
document 以載入,但是圖片和 stylesheets 和 frames 仍未載入

DOMContentLoaded
1
2
3
4
5
6
7
/*監聽,當 DOMContent 已經載入即觸發*/
document.addEventListener('DOMContentLoaded', function() {
console.log(document.readyState); /*比照上方會是 interactive*/
/*實測抓一個 html TagName <head>*/
let head = document.getElementsByTagName('head')
console.log(head);
});

Ref:

$(document).ready equivalent without jQuery: https://stackoverflow.com/a/18775368/7408485
Event reference 裡的 Update eventshttps://developer.mozilla.org/en-US/docs/Web/Events

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×