DIV CSS 佈局教程網

用 Ajax 動態載入所需的 JS 檔:打造一個迷你 require
編輯:AJAX基礎知識     

寫 Java 習慣了「要用什麼就 import」之後,回頭寫 JavaScript 難免覺得彆扭。dojo 的 dojo.require 當年把這個概念帶進了前端,但整套函式庫實在龐大,於是很多人乾脆自己刻一個小的:只做「按需載入 js 檔」這一件事。

三次失敗:document.write 的順序問題

最直接的想法是用 document.write 插入一個 script 標籤。寫是寫進去了,執行順序卻不對——它是在後面才插入,而我們往往在當下的程式碼裡立刻就要用被載入的東西,於是瀏覽器丟出「某某未定義」。本質上是同步與非同步的落差:document.write 無法讓後續程式碼等它。

第二次嘗試:同步 Ajax 抓檔再執行

接著改用 Ajax 同步(不是非同步)抓取遠端 js 檔,取回文字後再執行。這一條路走通了,過程中要處理三件事:

  1. 路徑參照。相對路徑到底相對於誰?可以相對於呼叫者,也可以相對於載入器本身。這個實作選擇「以 env.js 所在位置為參照」,並在初始化時用 document.location.pathname 加上 script 標籤的 src 推算出基準路徑。
  2. 編碼。抓回來的中文變亂碼。因為專案一律走 UTF-8,這個問題被繞了過去——換言之,若伺服器沒跟著統一編碼,這裡就會爆。
  3. 執行上下文。用 eval 執行後,發現遠端 js 裡定義的東西取不到。原因是 eval 的作用域不对,我們要的是在 window 上執行。IE 下可用 window.execScript,Firefox 則要用 window.eval;為了兩邊都穩,實作裡乾脆兩者並用。

env.js 的核心:三個單例

整個檔案分成三塊:Status 負責畫面中央的狀態提示層,Request 負責通訊(含通道與快取),Env 則是對外的 require 介面。

狀態提示層

var Status = new function () {
    this.statusDiv = null;

    // 建立一個置中、深藍底、圓角感的提示層
    this.init = function () {
        if (this.statusDiv != null) { return; }
        var body = document.getElementsByTagName("body")[0];
        var div = document.createElement("div");
        div.style.position = "absolute";
        div.style.top = "50%";
        div.style.left = "50%";
        div.style.width = "280px";
        div.style.margin = "-50px 0 0 -100px";
        div.style.padding = "15px";
        div.style.backgroundColor = "#353555";
        div.style.border = "1px solid #CFCFFF";
        div.style.color = "#CFCFFF";
        div.style.fontSize = "14px";
        div.style.textAlign = "center";
        div.id = "status";
        body.appendChild(div);
        div.style.display = "none";
        this.statusDiv = document.getElementById("status");
    };

    this.showInfo = function (_message) {
        if (this.statusDiv == null) { this.init(); }
        this.setStatusShow(true);
        this.statusDiv.innerHTML = _message;
    };

    this.setStatusShow = function (_show) {
        if (this.statusDiv == null) { this.init(); }
        if (_show) {
            this.statusDiv.style.display = "";
        } else {
            this.statusDiv.innerHTML = "";
            this.statusDiv.style.display = "none";
        }
    };
}

通訊層:建立物件與通道快取

function HttpRequestObject() {
    this.chunnel = null;   // 通道名稱
    this.instance = null;  // XMLHTTP 實例
}

var Request = new function () {
    this.showStatus = true;
    this.httpRequestCache = new Array();

    // 建立新的通訊物件:先試 Mozilla 原生,再逐一嘗試 IE 的 MSXML 版本
    this.createInstance = function () {
        var instance = null;
        if (window.XMLHttpRequest) {
            instance = new XMLHttpRequest();
            // 部分 Mozilla 版本在回應缺少 XML mime-type 時會出錯,主動覆寫
            if (instance.overrideMimeType) {
                instance.overrideMimeType("text/xml");
            }
        } else if (window.ActiveXObject) {
            var MSXML = ['MSXML2.XMLHTTP.5.0', 'Microsoft.XMLHTTP',
                         'MSXML2.XMLHTTP.4.0', 'MSXML2.XMLHTTP.3.0',
                         'MSXML2.XMLHTTP'];
            for (var i = 0; i < MSXML.length; i++) {
                try {
                    instance = new ActiveXObject(MSXML[i]);
                    break;
                } catch (e) {}
            }
        }
        return instance;
    };

    // 依通道名稱取用物件;不存在就建立並放進快取,方便同一通道的重複利用
    this.getInstance = function (_chunnel) {
        if (_chunnel == undefined) { _chunnel = "default"; }
        var instance = null, object = null, getOne = false;

        for (var i = 0; i < this.httpRequestCache.length; i++) {
            object = this.httpRequestCache[i];
            if (object.chunnel == _chunnel) {
                // 只有閒置(0)或已完成(4)的物件才能重用
                if (object.instance.readyState == 0 || object.instance.readyState == 4) {
                    instance = object.instance;
                }
                getOne = true;
                break;
            }
        }
        if (!getOne) {
            object = new HttpRequestObject();
            object.chunnel = _chunnel;
            object.instance = this.createInstance();
            this.httpRequestCache.push(object);
            instance = object.instance;
        }
        return instance;
    };

    // 送出請求:url、要送的資料、處理回應的函式、通道名、是否非同步
    this.send = function (_url, _data, _processRequest, _chunnel, _asynchronous) {
        if (_url.length == 0 || _url.indexOf("?") == 0) {
            Status.showInfo("由於目的為空,請求失敗,請檢查!");
            window.setTimeout("Status.setStatusShow(false)", 3000);
            return;
        }
        if (this.showStatus) { Status.showInfo("請求處理中,請稍候"); }
        if (_chunnel == undefined || _chunnel == "") { _chunnel = "default"; }
        if (_asynchronous == undefined) { _asynchronous = true; }

        var instance = this.getInstance(_chunnel);
        if (instance == null) {
            Status.showInfo("瀏覽器不支援 ajax,請檢查!");
            window.setTimeout("Status.setStatusShow(false)", 3000);
            return;
        }

        if (_asynchronous == true && typeof (_processRequest) == "function") {
            instance.onreadystatechange = function () {
                if (instance.readyState == 4) {
                    if (instance.status == 200) {
                        _processRequest(instance);
                        Status.setStatusShow(false);
                        Request.showStatus = true;
                    } else {
                        Status.showInfo("您所請求的頁面有異常,請檢查!");
                        window.setTimeout("Status.setStatusShow(false)", 3000);
                    }
                }
            };
        }

        // 掛上時戳參數,避免快取讓相同網址不再送出請求
        _url += (_url.indexOf("?") != -1 ? "&" : "?") + "requestTime=" + (new Date()).getTime();

        if (_data.length == 0) {
            instance.open("GET", _url, _asynchronous);
            instance.send(null);
        } else {
            instance.open("POST", _url, _asynchronous);
            instance.setRequestHeader("Content-Length", _data.length);
            instance.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            instance.send(_data);
        }

        // 同步模式下,send 返回時資料已經到齊,直接呼叫回呼即可
        if (_asynchronous == false && typeof (_processRequest) == "function") {
            _processRequest(instance);
            Request.showStatus ? Status.setStatusShow(false) : (Request.showStatus = true);
        }
    };

    // 每隔一段時間重複發送(僅限非同步、GET)
    this.intervalSend = function (_interval, _url, _processRequest, _chunnel) {
        var action = function () {
            if (_chunnel == undefined) { _chunnel = "defaultInterval"; }
            var instance = Request.getInstance(_chunnel);
            if (instance == null) { return; }
            if (typeof (_processRequest) == "function") {
                instance.onreadystatechange = function () {
                    if (instance.readyState == 4 && instance.status == 200) {
                        _processRequest(instance);
                    }
                };
            }
            var u = _url + (_url.indexOf("?") != -1 ? "&" : "?")
                    + "requestTime=" + (new Date()).getTime();
            instance.open("GET", u, true);
            instance.send(null);
        };
        window.setInterval(action, _interval);
    };
}

Env:對外的 require 介面

var Env = new function () {
    this.funcList = new Array();  // 已載入清單,避免重複載入
    this.envPath = null;

    // 以 env.js 自身的位置作為相對路徑的參照
    this.getPath = function () {
        this.envPath = document.location.pathname;
        this.envPath = this.envPath.substring(0, this.envPath.lastIndexOf("/") + 1);

        var _scripts = document.getElementsByTagName("script");
        var _scriptSrc = null;
        for (var i = 0; i < _scripts.length; i++) {
            _scriptSrc = _scripts[i].getAttribute("src");
            if (_scriptSrc && _scriptSrc.indexOf("env.js") != -1) { break; }
        }
        if (_scriptSrc != null) {
            if (_scriptSrc.charAt(0) == '/') {
                this.envPath = _scriptSrc.substr(0, _scriptSrc.length - 6);
            } else {
                this.envPath = this.envPath + _scriptSrc.substr(0, _scriptSrc.length - 6);
            }
        }
    };
    this.getPath();

    // 按需載入 js;路徑可用絕對或相對(相對於 env.js)
    this.require = function (_jsName, _language) {
        var _absJsName = (_jsName.charAt(0) == '/') ? _jsName : this.envPath + _jsName;

        if (Env.funcList[_absJsName]) { return; }   // 已載入過就跳過
        Env.funcList[_absJsName] = "finished";

        var processJs = function (_instance) {
            // 要在 window 上執行,IE 用 execScript,Firefox 用 window.eval
            if (window.execScript) {
                _language ? window.execScript(_instance.responseText, _language)
                          : window.execScript(_instance.responseText);
            } else {
                _language ? window.eval(_instance.responseText, _language)
                          : window.eval(_instance.responseText);
            }
        };

        Request.showStatus = false;   // 載入 js 時不顯示提示層
        Request.send(_absJsName, "", processJs, "", false);  // 同步,確保立刻可用
    };

    // 另一種做法:在當前 script 之後插入一個新的 script 標籤
    this.getJs = function (_jsName) {
        if (!Env.funcList[_jsName]) {
            Env.funcList[_jsName] = "finished";
            document.write('<scr' + 'ipt type="text/javascript" src="' + _jsName + '"></' + 'scr' + 'ipt>');
        }
    };
}

補救措施:讓被插入的 script 真正執行

用 Ajax 抓回整頁 HTML 時,其中的 script 標籤不會自動執行。reloadJs 的作法是掃過所有 script 節點,有 src 的就重建一個 script 元素掛回去,沒 src 的就用 execScript / window.eval 直接跑它的 text:

function reloadJs(_language) {
    var _c = document.getElementsByTagName("SCRIPT");
    for (var i = 0; i < _c.length; i++) {
        if (_c[i].src) {
            var _s = document.createElement("script");
            _s.type = "text/javascript";
            _s.src = _c[i].src;
            // 不用 insertAdjacentElement,那是 IE 專屬
            _c[0].parentNode.insertBefore(_s, _c[0]);
            _c[i].parentNode.removeChild(_c[i]);
        } else if (_c[i].text) {
            if (window.execScript) {
                _language ? window.execScript(_c[i].text, _language)
                          : window.execScript(_c[i].text);
            } else {
                _language ? window.eval(_c[i].text, _language)
                          : window.eval(_c[i].text);
            }
        }
    }
}

怎麼用

需要用到其他 js 時,寫 Env.require("cookie.js") 或 Env.require("/common/cookie.js") 都可以,相對或絕對看個人喜好。它既能寫在頁面模板裡,也能寫在 js 檔中,唯一的前提是執行當下 env.js 必須已被明確引入。同一個 js 無論用相對或絕對路徑 require 多少次,只有第一次會真的載入,因此不會重複。

今天回頭看這份程式碼

這個實作的思路——路徑解析、去重快取、同步確保可用、跨瀏覽器執行——正是後來 AMD、CommonJS 到 ES Module 都在解決的同一組問題。差別在於現代方案用原生 <script type="module"> 與 import 語法就把「非同步載入 + 依賴解析 + 快取」交給瀏覽器處理,不必再手刻。

另外要提醒的是:同步 Ajax 會凍結整個 UI 執行緒,這是它最大的缺點,也是當年為了「立刻可用」所付的代價。若今天要在新專案裡做類似的事,正確答案幾乎一定是動態 import(import("./mod.js").then(...))或打包工具的程式碼分割,而不是同步 XHR。把這份程式碼當成歷史案例來讀,理解每個設計背後的取捨,比直接複製更有價值。

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