萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery Cookie 插件載入順序錯誤排查:必須在 jQuery 之後載入

問題現象

引入 jquery.cookie.js 後呼叫 $.cookie() 報錯 Uncaught TypeError: $.cookie is not a function,但程式碼語法無誤。

根本原因

jQuery 插件掛載在 jQuery.fn 或 jQuery 命名空間上,**必須在 jQuery 核心庫載入完成後**才能正確擴充。若載入順序顛倒,插件執行時 jQuery 尚未定義,導致掛載失敗。

正確載入順序

<head>
    <!-- 1. 先載入 jQuery 核心 -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

    <!-- 2. 再載入依賴 jQuery 的插件 -->
    <script src="/Scripts/jquery.cookie.js"></script>

    <!-- 3. 最後載入使用插件的業務代碼 -->
    <script src="/js/app.js"></script>
</head>

常見錯誤場景

  • 在 webpack/vite 等打包工具中,未正確配置 providePlugin 或 import 順序。
  • 使用 async/defer 導致執行順序不確定:
    <script defer src="jquery.js"></script>
    <script defer src="jquery.cookie.js"></script>
    → 瀏覽器保證按順序執行,**可行**。
    <script async src="jquery.js"></script>
    <script async src="jquery.cookie.js"></script>
    → **順序不保證,極大機率失敗**。
  • 多版本 jQuery 共存(如 jQuery.noConflict()),插件掛載到錯誤版本實例。

現代模組化寫法(ESM / CommonJS)

// npm i jquery jquery-cookie
import $ from 'jquery';
import 'jquery-cookie'; // 側邊效應模組,自動掛載到 $

// 或 CommonJS
const $ = require('jquery');
require('jquery-cookie');

// 使用
$.cookie('token', 'abc123', { expires: 7, path: '/' });

替代方案:原生 Cookie API / js-cookie

  • 原生:document.cookie 需手動解析,推薦封裝 getCookie/setCookie 工具函數。
  • js-cookie:npm i js-cookie,輕量、無 jQuery 依賴、TypeScript 友善、支援模組化。
    import Cookies from 'js-cookie'; Cookies.set('token', 'abc');

快速檢查清單

  1. Network 面板確認 jquery.js 狀態 200、在 jquery.cookie.js **之前**載入完成。
  2. Console 輸入 typeof $.cookie 應為 "function"。
  3. 若仍失效,檢查是否有多個 jQuery 實例($.fn.jquery 版本號)。
copyright © 萬盛學電腦網 all rights reserved