5.2 載入(Load)的相關事件

DOMContentLoaded

javascript:

document.addEventListener("DOMContentLoaded", function(){
  // DOM 載入完成之後
});

jQuery:

// 寫法一
$(document).ready(function() {
  // DOM 載入完成之後
});

// 寫法二
$(function(){
  // DOM 載入完成之後
});

load

javascript:

window.addEventListener("load", function(){
  // 圖片等資源載入完成之後
});

jQuery:

$(window).on("load", function(){
  // 圖片等資源載入完成之後
});

resize

JavaScript:

window.addEventListener("resize", function(){
  // 瀏覽器的寬高有改變時觸發
});

jQuery:

$(window).on("resize", function(){
  // 瀏覽器的寬高有改變時觸發
});

實測比較

範例 1:

範例 2:

建立 windowload.html 內容如下,測試看看:

一個動畫區域蓋住整個頁面,等到所有東西都渲染完之後,才將動畫區域給移除,就適合用 load 事件。

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>window load 事件</title>
    <style>
      * {
        box-sizing: border-box;
      }
  
      @keyframes twinkle{
        0%{
          opacity: .1;
        }
        100%{
          opacity: 1;
        }
      }
  
      p.para{
        font-size: 32px;
        color: red;
        font-weight: bold;
        font-style: italic;
        font-family: "Helvetica Neue";
        margin: 0;
        
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
      }
      span.dot{
        display: inline-block;
        width: 10px;
        height: 10px;
        border-radius: 50%;
        background-color: red;
        position: relative;
        top: 3px;
        left: -3px;
        
        animation-name: twinkle;
        animation-duration: .8s;
        animation-timing-function: ease-in-out;
        animation-iteration-count: infinite;
        animation-direction: alternate;
        
      }
      span.-dot2{
        animation-delay: .2s;
      }
      span.-dot3{
        animation-delay: .4s;
      }
  
      div.loading_block{
        border: 2px solid blue;
        position: fixed;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        background-color: hsla(0, 0%, 0%, .8);
      }
    </style>
  </head>
  <body>
    <section>這是頁面中的其它區域</section>
    <img src="https://alldata.sgp1.digitaloceanspaces.com/images/mountain.jpg" id="my_img"><!-- 這張圖有 6M 的大小 -->
  
    <div class="loading_block">
      <p class="para">
        Loading
        <span class="dot -dot1"></span>
        <span class="dot -dot2"></span>
        <span class="dot -dot3"></span>
      </p>
    </div>
  
    <script>
      window.addEventListener("load", function(){
        document.getElementsByClassName("loading_block")[0].remove();
      });
    </script>
  </body>
</html>

Last updated