做過 UI 的人大概都遇過這件事:IE(不含 IE7)動不動就回伺服器重新抓一次背景圖,好端端的介面被折騰得不停閃爍。
Pixy 的圓角方案常被說會受 IE 快取 bug 影響而閃爍,但這個說法其實漏了前提:該 bug 只在 IE 的快取設定被改成「每次造訪頁面時檢查更新」(Every visit to the page)而非預設的「自動」(Automatically)時才會發生。會去改這個設定的基本上只有開發者,因此真實使用者多半不會碰到(在 winxp sp2 的 IE6 上實測,雖然仍可能呼叫一次網路存取 API,但並未真正發出請求,症狀僅是滑鼠極短暫的抖動,圖片本身不會閃爍)。
社群流傳一個未公開的呼叫,可以讓 IE 把背景圖快取住:
document.execCommand("BackgroundImageCache", false, true);
據說它連 API 呼叫都省了,感覺是直接快存在 IE 記憶體裡。IE6 下設定背景圖片本來不會被真正快取,就算伺服器端做了 cache 也一樣,而這行語法正是繞過這個限制的方式。
Erik 發現了這個簡便解法(對 IE7 以下有效,IE7 已修掉此 Bug):
document.execCommand("BackgroundImageCache", false, true);
讀 Ext 原始碼時發現 Jack Slocum 早就把這點考慮進去了,Ext.js 中的寫法是:
var isIE = ua.indexOf("msie") > -1,
isIE7 = ua.indexOf("msie 7") > -1;
// remove css image flicker
if (isIE && !isIE7) {
try {
document.execCommand("BackgroundImageCache", false, true);
} catch (e) {}
}
當時其他 Ajax 框架似乎還沒有類似處理,從這一個細節就能看出 Ext 的細緻程度。
另外,讀幻宇的 dreamplayer 播放器原始碼時,也看到他針對 IE 背景快取做了修復,只是沒意識到 IE7 已不存在此現象。evml.js 中的相關片段:
window.isIE = navigator.appName.indexOf("Microsoft") == 0;
if (isIE) {
document.documentElement.addBehavior("#default#userdata");
document.execCommand("BackgroundImageCache", false, true);
}
英文社群當時也熱烈討論過這個 workaround:
A while back a lot of people were covering how to work around the bug that IE always reloads background images from the server, leading to your UI flickering. Today I saw this simple workaround:
document.execCommand("BackgroundImageCache", false, true)
Much simpler, but makes me wonder why this is not the default setting?
Nicholas C. Zakas 在 2007-02-26 的回覆則點出了另一個角度:
I've actually wondered about this "bug" for a while. I'm sure somewhere along the line this decision was made for a logical reason... maybe they didn't anticipate how much background images would be used, or maybe they thought there was some use case under which it would be desirable not to cache the background image. I've never really thought this was a "bug"... bugs don't usually have switches that say "turn off bug".
這個觀點值得記住:一個行為若能被一行設定關掉,它更可能是設計取捨而非缺陷。無論如何,在需要支援舊版 IE 的年代,這行 execCommand 都是值得放進專案初始化的實用防護。