原生 js 实现类似 jQuery (document).ready () 方法

  • 具体方法如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
document.ready = function (callback) {
if (document.addEventListener) {
const handler = function () {
document.removeEventListener('DOMContentLoaded', handler, false);
callback();
};
document.addEventListener('DOMContentLoaded', handler, false);
} else if (document.attachEvent) {
const handler = function () {
if (document.readyState === "complete") {
document.detachEvent('onreadystatechange', handler);
callback();
}
};
document.attachEvent('onreadystatechange', handler);
} else if (document.lastChild === document.body) {
callback();
}
};
  • 调用
1
document.ready(function(){});