需要使用 document.readyState, 它可以判断网页的加载情况, 如果网页加载完成, document.readyState 就会返回 'complete';
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <img src="https://pic.cnblogs.com/face/1725689/20190826182819.png" alt=""> <script> document.addEventListener("readystatechange", function (e) { if (e.target.readyState === 'complete') { console.log("加载完成"); } else { console.log("正在加载"); } }) </script> </body> </html>
注意:
1. 每次 document.readyState 值的改变都会触发 readystatechange 事件.
2. 也可以使用 setInterval() 实现同样的功能.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <script> var interval = setInterval(function () { if (document.readyState === 'complete') { clearInterval(interval); console.log('加载完成'); } else { console.log('正在加载'); } }, 100); </script> <img src="https://pic.cnblogs.com/face/1725689/20190826182819.png" alt=""> </body> </html>