DIV CSS 佈局教程網

動態載入 jQuery 的兩種寫法:含載入完成檢測
編輯:關於JavaScript     

寫使用者腳本或需要延遲載入函式庫時,時常得在執行階段才把 jQuery 掛進頁面。以下是兩種實用寫法,一種輕量、一種處理了 $ 衝突。

寫法一:加上載入狀態檢測

function withjQuery(callback) {
  if (!(window.jQuery)) {
    var js = document.createElement('script');
    js.setAttribute('src', 'https://dynamic.12306.cn/otsweb/js/common/jquery-1.4.2.min.js?version=5.47');
    js.setAttribute('type', 'text/javascript');
    js.onload = js.onreadystatechange = function () {
      if (!this.readyState || this.readyState === 'loaded' || this.readyState === 'complete') {
        if (callback && typeof callback === "function") { callback(); }
        js.onload = js.onreadystatechange = null;   // 避免重複觸發與記憶體洩漏
      }
    };
    document.getElementsByTagName('head')[0].appendChild(js);
  }
}

withjQuery(function () {
  $(function () { alert("jQuery loaded"); })();
});

兩個細節:onreadystatechange 是為了舊 IE,而 readyState 的三種取值判斷是為了避免同一個回呼被觸發多次;跑完立刻把 handler 設為 null,是常見的收尾習慣。

寫法二:處理 $ 衝突的版本

這個版本來自 12306 刷票腳本,多了 safe 參數,用來避免覆蓋頁面原有的 $:

// ==UserScript==
// @name         12306 Booking Assistant
// @version      1.4.0
// @description  12306 訂票助手(自動登錄、自動查票、自動訂單)
// @include      *://dynamic.12306.cn/otsweb/*
// @require      https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js
// ==/UserScript==

function withjQuery(callback, safe) {
  if (typeof (jQuery) == "undefined") {
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src = "https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js";

    if (safe) {
      // 安全模式:載入後立刻 noConflict,把 jQuery 當參數傳進回呼
      var cb = document.createElement("script");
      cb.type = "text/javascript";
      cb.textContent = "jQuery.noConflict();(" + callback.toString() + ")(jQuery, window);";
      script.addEventListener('load', function () {
        document.head.appendChild(cb);
      });
    } else {
      // 一般模式:先記下原本的 $,跑完再還回去
      var dollar = undefined;
      if (typeof ($) != "undefined") dollar = $;
      script.addEventListener('load', function () {
        jQuery.noConflict();
        $ = dollar;
        callback(jQuery, window);
      });
    }
    document.head.appendChild(script);
  } else {
    setTimeout(function () {
      callback(jQuery, typeof unsafeWindow === "undefined" ? window : unsafeWindow);
    }, 30);
  }
}

withjQuery(function ($, window) {
  $(function () { alert("jQuery loaded"); })();
}, true);

兩種寫法的取捨很清楚:頁面就是自己的,用寫法一即可;要掛到別人的網站上(例如使用者腳本),務必用寫法二,否則很可能把原站的 $ 搶走,讓對方功能全掛。setTimeout(..., 30) 那段則是給「jQuery 已存在但尚未完全初始化」的情況留一點緩衝。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved