document.lastModified 回傳字串,格式為 "MM/DD/YYYY HH:MM:SS" (美式日期格式),代表文檔最後修改時間。來源為 HTTP 響應標頭 Last-Modified,若無則為當前時間。本文說明用法、格式化、快取關係與注意事項。
const lastMod = document.lastModified; // "04/03/2015 02:42:22"
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Last Modified 範例</title>
</head>
<body>
<p>本頁最後更新:<span id="lm"></span></p>
<script>
document.getElementById('lm').textContent = document.lastModified;
</script>
</body>
</html>
function formatLastModified(str) {
// "MM/DD/YYYY HH:MM:SS"
const [datePart, timePart] = str.split(' ');
const [month, day, year] = datePart.split('/');
return `${year}-${month.padStart(2,'0')}-${day.padStart(2,'0')} ${timePart}`;
}
console.log(formatLastModified(document.lastModified)); // "2015-04-03 02:42:22"
const d = new Date(document.lastModified);
console.log(d.toLocaleString()); // 依瀏覽器語系顯示,如 "2015/4/3 上午10:42:22"
console.log(d.toISOString()); // "2015-04-03T02:42:22.000Z" (UTC)
Last-Modified。Cache-Control: max-age) 下,若瀏覽器直接讀取快取不發請求,lastModified 可能不更新。Last-Modified,通常回傳腳本執行時間或檔案修改時間。<footer>
<small>內容最後更新:<span id="lastUpdate"></span></small>
</footer>
<script>
document.getElementById('lastUpdate').textContent =
new Date(document.lastModified).toLocaleDateString('zh-TW', {year:'numeric',month:'long',day:'numeric'});
</script>
// Service Worker 中攔截請求,若文檔未修改可直接回傳快取
self.addEventListener('fetch', e => {
if (e.request.url.endsWith('.html')) {
e.respondWith(caches.match(e.request).then(cached => {
if (cached) {
const lastMod = cached.headers.get('last-modified');
// 可與 document.lastModified 比對 (需同源)
}
return cached || fetch(e.request);
}));
}
});
// 協同編輯時,定期輪詢 document.lastModified,若變更提示用戶重新載入
setInterval(() => {
fetch(location.href, {method:'HEAD'}).then(r => {
const serverMod = r.headers.get('last-modified');
if (serverMod && new Date(serverMod) > new Date(document.lastModified)) {
alert('文檔已被他人更新,請重新整理。');
}
});
}, 30000);
| 限制 | 說明 | 對策 |
|---|---|---|
| 格式固定美式 | MM/DD/YYYY HH:MM:SS,不支援本地化 | 用 Date 解析後 toLocaleString |
| 精度只到秒 | 無毫秒資訊 | 需更高精度請用 HTTP 標頭或版本號 |
| 依賴伺服器標頭 | 無 Last-Modified 標頭則不準 | 後端務必輸出正確標頭 |
| 跨域 iframe 無法讀取 | 安全限制 | 同源才能存取 |
| SPA 路由切換不更新 | document 不變,lastModified 不變 | 自行維護版本狀態 |
document.lastModified 是零成本顯示頁面更新時間的方法,但**極度依賴後端正確輸出 Last-Modified 標頭**。動態站點務必在後端根據資料庫更新時間、檔案修改時間或模板編譯時間設定此標頭。前端配合 Date 解析與 toLocaleString 即可呈現友善格式。