Skip to content

Instantly share code, notes, and snippets.

@FlandreDaisuki
Forked from ipcjs/dom_load_order.user.js
Created October 22, 2017 10:48
Show Gist options
  • Save FlandreDaisuki/87da8921dc785a9e003aa1c0bb2dd7cc to your computer and use it in GitHub Desktop.
Save FlandreDaisuki/87da8921dc785a9e003aa1c0bb2dd7cc to your computer and use it in GitHub Desktop.
Dom相关事件的执行顺序
// ==UserScript==
// @name New Userscript
// @namespace https://github.com/ipcjs
// @version 0.0.1
// @description try to take over the world!
// @author ipcjs
// @match http://bangumi.bilibili.com/anime/5788/play*
// @grant none
// @run-at document-start
// ==/UserScript==
(function () {
'use strict';
window.addEventListener('load', (...args) => {
console.log(7, document.readyState, args, document.getElementById('index_nav'));
});
window.addEventListener('DOMContentLoaded', (...args) => {
console.log(5, document.readyState, args, document.getElementById('index_nav'));
});
document.addEventListener('readystatechange', (...args) => {
console.log(1, document.readyState, args, document.getElementById('index_nav'));
});
document.addEventListener('DOMContentLoaded', (...args) => {
console.log(3, document.readyState, args, document.getElementById('index_nav'));
});
document.addEventListener('DOMContentLoaded', (...args) => {
console.log(4, document.readyState, args, document.getElementById('index_nav'));
});
window.addEventListener('DOMContentLoaded', (...args) => {
console.log(6, document.readyState, args, document.getElementById('index_nav'));
});
document.addEventListener('readystatechange', (...args) => {
console.log(2, document.readyState, args, document.getElementById('index_nav'));
});
window.addEventListener('load', (...args) => {
console.log(8, document.readyState, args, document.getElementById('index_nav'));
});
})();
@FlandreDaisuki
Copy link
Author

結論

order target event document.readyState
1 document readystatechange interactive
2 document DOMContentLoaded interactive
3 window DOMContentLoaded interactive
4 document readystatechange complete
5 window load complete

其中 2 和 3 的關係是因為事件 bubble,根據 whatwg:
DOMContentLoaded這頁

12.2.7 The end

  1. Queue a task to run the following substeps:
  1. Fire an event named DOMContentLoaded at the Document object, with its bubbles attribute initialized to true.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment