HTML:页面显示之前执行JS方法

一、方法:

  1. 把方法写在head中
  2. onload方法
  3. jq提供的ready() 方法
  4. document.addEventListener(“DOMContentLoaded”,console.log(123), false);

执行顺序: head > ready = DOMContentLoaded > onload

二、示例:

<!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">
  <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
  <script>
    console.log("head")
  </script>
  <title>html页面显示之前执行js方法</title>
</head>
<body>
  <script>
    window.onload = function () {
      console.log("onload")
    }
    $(document).ready(
      console.log('ready')
    )
    document.addEventListener("DOMContentLoaded", console.log('DOMContentLoaded'), false);
    // 执行顺序 head > ready = DOMContentLoaded > onload
    // head
    // ready
    // DOMContentLoaded
    // onload
  </script>
</body>
</html>
posted @ 2025-05-12 13:29  Dy大叔  阅读(19)  评论(0)    收藏  举报