非同步請求進行時,使用者需要一個明確的「正在處理」回饋,否則很容易以為系統沒有反應而重複點擊。以下實作一個會自動計算視窗置中位置、並隨頁面捲動對齊的載入提示層。
function loading(p_value, str)
{
if (p_value)
{
if (!document.getElementById("load_area"))
{
var para1 = document.createElement("span");
var node = document.createTextNode(str);
para1.appendChild(node);
var para = document.createElement("div");
para.id = "load_area";
var top = document.body.scrollTop + document.documentElement.scrollTop;
para.style.top = (top + 157) + "px";
para.style.cssText +=
";position:absolute;left:50%;width:140px;margin-left:-70px;height:50px;" +
"line-height:50px;font-size:18px;text-overflow:ellipsis;overflow:hidden;" +
"white-space:nowrap;text-align:center;background-color:#000;" +
"border-radius:2px;-webkit-box-shadow:0 2px 2px rgba(0,0,0,0.5);color:#eee;";
var icon = new Image();
icon.src = "images/loading1.gif"; // 替換為實際路徑
icon.style.cssText += ";vertical-align:middle;padding-right:4px;margin-top:-2px;";
document.body.appendChild(para);
para.appendChild(icon);
para.appendChild(para1);
}
else
{
document.getElementById("load_area").style.display = "block";
}
}
else
{
document.getElementById("load_area").style.display = "none";
}
}
loading(true, "加載中..."); // 顯示 loading(false); // 隱藏
變數宣告時機。原實作中 icon 在建立 para 之後才宣告,卻在更早的地方被引用,這是靠 var 提升僥倖不報錯,實際上順序是有問題的。養成「宣告在使用之前」的習慣能避免這類隱患。
定位方式。用 position:absolute 搭配手動計算 scrollTop,頁面一捲動提示層就會「留在原處」,體感很差。改用 position:fixed 就不需要任何計算:
#load_area {
position: fixed;
top: 50%; left: 50%;
transform: translate(-50%, -50%);
/* 以下樣式沿用原版 */
}
transform: translate(-50%, -50%) 取代了 margin-left:-70px 這種綁死寬度的做法,提示層寬度日後要改也不必再算一次。
遮罩。目前的實作只是一個小方塊浮在上面,使用者仍然可以點擊背後的按鈕,可能送出重複請求。完整的載入狀態通常還需要一層半透明遮罩攔住所有互動。
這個元件用 <dialog> 實作會乾淨很多,模態顯示時會自動加上遮罩並阻斷背景操作:
// HTML: <dialog id="loading">載入中...</dialog>
var box = document.getElementById('loading');
function showLoading() { box.showModal(); }
function hideLoading() { box.close(); }
另外提醒一個實務重點:載入提示必須搭配逾時處理。若請求因網路問題掛住,而提示層永遠不關,使用者只會 reload 整個頁面。用 AbortController 設定逾時並在 finally 區塊中確保關閉,是比較穩健的寫法:
showLoading();
try {
await fetch(url, { signal: AbortSignal.timeout(10000) });
} catch (e) {
console.error(e);
} finally {
hideLoading(); // 無論成功失敗都要關
}