在頁面上建立 ActiveXObject 的代價並不便宜。當無刷新頁面大量使用 xmlhttp 時,我們可能需要頻繁建立物件。
一個常見的折衷是用全域變數快取單一 xmlhttp 實例。但這招只適合同步通訊。在異步模式下,由於沒有行程阻塞,使用者很可能在前一次通訊尚未結束時又觸發第二次呼叫;這時兩個操作共用同一個實例,前一次就必然失敗。
建立一個 pool 來管理頁面上的 xmlhttp 實例,有兩個明顯好處:不會再建立冗餘物件,也不會出現多個操作同時落在同一個忙碌實例上的情況。
實作方式很直觀:用一個陣列當 pool 存放已建立的實例,每次呼叫時從中挑一個可用的。通訊結束後不必特別回收,因為 readyState 本來就能標示它是否可用;若當時沒有空閒實例,且 pool 中數量還沒超過 m_MaxPoolLength,就建立一個新的放進去。
var __XmlHttpPool__ = {
m_MaxPoolLength : 10,
m_XmlHttpPool : [],
__requestObject : function () {
var xmlhttp = null;
// 先從 pool 中找一個 readyState 為 0 或 4 的可用實例
for (var i = 0; i < this.m_XmlHttpPool.length; i++) {
var item = this.m_XmlHttpPool[i];
if (item.readyState == 0 || item.readyState == 4) {
return item;
}
}
// 沒有空閒實例時,視情況建立新物件
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
try {
xmlhttp = new XMLHttpRequest(); // 標準瀏覽器
} catch (e3) {
xmlhttp = null;
}
}
}
if (xmlhttp != null && this.m_XmlHttpPool.length < this.m_MaxPoolLength) {
this.m_XmlHttpPool.push(xmlhttp);
}
return xmlhttp;
}
};
取用時只要呼叫 __XmlHttpPool__.__requestObject() 就能拿到一個可用實例,後續的 open/send/onreadystatechange 流程與平常無異。上限值 m_MaxPoolLength 可依頁面併發需求調整:設太小會頻繁建立物件,設太大則白佔記憶體。
這個模式在單頁中同時有多個獨立異步請求(例如多個下拉選單各自去伺服器取資料)時特別有用,能有效避免回呼互相踩到彼此的狀態。