<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Loading 效果 Demo</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { background: #000; font-family: Arial, sans-serif; }
/* Loading 容器:固定定位、置中 */
#loadbox {
position: fixed; top: 50%; left: 50%;
transform: translate(-50%, -50%);
width: 220px; height: 60px;
text-align: center; z-index: 9999;
}
#loadbox span {
display: block; width: 100%; height: 32px;
line-height: 32px; color: #ccc; font-size: 14px;
}
#loadbox img { vertical-align: middle; }
/* 內容區:初始隱藏 */
#content { display: none; }
/* 現代 CSS Loading 動畫 (可替換 GIF) */
.spinner {
width: 40px; height: 40px; margin: 0 auto 10px;
border: 3px solid #333; border-top-color: #0099cc;
border-radius: 50%; animation: spin 1s linear infinite;
}
@keyframes spin { to { transform: rotate(360deg); } }
</style>
</head>
<body>
<!-- Loading 介面 -->
<div id="loadbox">
<span>頁面載入中,請稍候...</span>
<div class="spinner"></div>
<!-- 或使用 GIF:
-->
</div>
<!-- 實際內容 -->
<div id="content">
<iframe src="https://example.com" width="100%" height="400" frameborder="0"></iframe>
</div>
<script>
window.onload = function() {
// 簡單淡出動畫
var loadbox = document.getElementById('loadbox');
var content = document.getElementById('content');
loadbox.style.transition = 'opacity 0.3s ease';
loadbox.style.opacity = '0';
setTimeout(function() {
loadbox.style.display = 'none';
content.style.display = 'block';
}, 300);
};
</script>
</body>
</html>
<!-- 引入 Pace -->
<script src="https://cdn.jsdelivr.net/npm/pace-js@1.0.2/pace.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/pace-js@1.0.2/themes/blue/pace-theme-minimal.css">
<!-- 配置 -->
<script>
window.paceOptions = {
ajax: { trackMethods: ['GET', 'POST'] }, // 監聽 AJAX
document: true, // 監聽 DOMContentLoaded
restartOnPushState: true, // SPA 路由切換重啟
restartOnRequestAfter: 500 // 防抖
};
</script>
零配置自動顯示進度條,支援 SPA、AJAX、圖片載入等。
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/nprogress@0.2.0/nprogress.css">
<script src="https://cdn.jsdelivr.net/npm/nprogress@0.2.0/nprogress.js"></script>
<script>
// AJAX 開始/結束攔截 (jQuery 範例)
$(document).ajaxStart(function() { NProgress.start(); });
$(document).ajaxStop(function() { NProgress.done(); });
// 或手動控制
NProgress.start();
// ... 非同步操作 ...
NProgress.done();
| 方案 | 優點 | 缺點 | 適用場景 |
|---|---|---|---|
| 原生 onload + 手寫 Loading | 零依賴、完全可控、體積極小 | 需手動管理、無法感知 AJAX | 靜態頁、簡單專案、不想引入庫 |
| Pace.js | 自動監聽 AJAX/導航、主題豐富 | ~4KB、配置較多 | 傳統多頁應用、jQuery 專案 |
| NProgress | 極輕量 (~2KB)、頂部進度條體驗佳 | 需手動掛鉤 AJAX/路由 | SPA、現代專案、YouTube 風格 |
| Spin.js | 純 JS 生成 Canvas/Vector spinner、無圖片 | 需自行控制顯示/隱藏 | 需自定義 spinner 樣式 |