DIV CSS 佈局教程網

用 JavaScript 做出「頁面正在載入」的等待提示
編輯:關於JavaScript     

AJAX 應用常遇到一個問題:伺服器還在處理,畫面上什麼都沒動,使用者以為當機了。解法是在要求送出前先顯示一個「正在載入…」的提示,收到回應後再收起來。本文示範在 ASP.NET 的 code-behind 裡動態輸出這段腳本的做法。

為什麼要從伺服器端輸出?

因為提示訊息要在頁面「還是空白」的時候就出現。若在 Page_Load 才輸出,只要請求還沒回來,整頁 HTML 都不存在,自然沒東西可顯示。因此做法是:先寫出一個隱藏的容器與啟動腳本,並立刻 Flush 讓它送出,後續耗時的處理才接著跑。

程式碼

private void Page_Load(object sender, System.EventArgs e)
{
    Response.Write("<div id='mydiv'>");
    Response.Write("_");
    Response.Write("</div>");
    Response.Write("<script>mydiv.innerText = '';</script>");

    Response.Write("<script language=javascript>;");

    // 點會一直增加,超過上限就回到 1,形成循環動畫
    Response.Write("var dots = 0;var dotmax = 10;");
    Response.Write("function ShowWait(){");
    Response.Write("  var output = '正在載入頁面';dots++;");
    Response.Write("  if(dots >= dotmax) dots = 1;");
    Response.Write("  for(var x = 0;x < dots;x++){ output += '·'; }");
    Response.Write("  mydiv.innerText = output;");
    Response.Write("}");

    Response.Write("function StartShowWait(){");
    Response.Write("  mydiv.style.visibility = 'visible';");
    Response.Write("  window.setInterval('ShowWait()',1000);");
    Response.Write("}");

    Response.Write("function HideWait(){");
    Response.Write("  mydiv.style.visibility = 'hidden';");
    Response.Write("  window.clearInterval();");
    Response.Write("}");

    Response.Write("StartShowWait();</script>");

    Response.Flush();   // 這一句是最關鍵的
}

耗時的按鈕事件裡,通常在開工前呼叫 StartShowWait(),做完再呼叫 HideWait():

private void Button1_Click(object sender, System.EventArgs e)
{
    // 這裡放耗時的處理…
}

三個關鍵細節

Response.Flush() 是重點。沒有它,前面的字串會和後面的內容一起被緩衝,直到整頁準備好才一次送出,等待提示就完全失去意義。

計時器要記得清掉。setInterval 一旦啟動就會一直跑,如果不在 HideWait() 裡 clearInterval,即使提示隱藏了,背景仍然每秒執行一次,白白消耗資源。更嚴謹的做法是把 interval 的識別碼存起來(var tid = window.setInterval(...))再定點清除,而不是像範例這樣無參數呼叫。

用 innerText 有相容性風險。innerText 是 IE 的延伸屬性,標準寫法應是 textContent。此外,把大量 JavaScript 用 Response.Write 一段段拼出來非常難維護,實務上更乾淨的做法是把腳本放在外部 .js 檔裡,再用 ClientScriptManager.RegisterStartupScript 註冊,只把必要的參數注入進去。

最後,等待提示屬於狀態回饋,應該要有無障礙考量:替容器加上 role="status" 與 aria-live="polite",螢幕閱讀器才會把「正在載入」唸出來。

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