判斷是否為 IE:
if (document.all) { alert("這是 IE 瀏覽器"); }
判斷是否為 IE6:
// 方法一
if ( /MSIE 6.0/ig.test(navigator.appVersion) ) { alert("這是 IE6 瀏覽器"); }
// 方法二
var IE = !+'\v1';
IE6 = IE && ([/MSIE(\d)\.0/i.exec(navigator.userAgent)][0][1] == 6)
判斷是否為 IE7:
if ( /MSIE 7.0/ig.test(navigator.appVersion) ) { alert("這是 IE7 瀏覽器"); }
其他 IE 版本同理類推。
var _uat = navigator.userAgent;
if (_uat.indexOf("MSIE 6.0") > 0) alert("ie6");
else if (_uat.indexOf("MSIE 7.0") > 0) alert("ie7");
else if (_uat.indexOf("MSIE 8.0") > 0) alert("ie8");
else if (_uat.indexOf("Firefox") > 0) alert("firefox");
#example { color:red; } /* firefox */
* html #example { color:blue; } /* ie6 */
*+html #example { color:green; } /* ie7 */
<!--[if !IE]><!--> 除 IE 外都可識別 <!--<![endif]--> <!--[if IE]> 所有 IE 可識別 <![endif]--> <!--[if IE 6]> 僅 IE6 可識別 <![endif]--> <!--[if lt IE 6]> IE6 及以下可識別 <![endif]--> <!--[if gte IE 6]> IE6 及以上可識別 <![endif]--> <!--[if IE 7]> 僅 IE7 可識別 <![endif]--> <!--[if lt IE 7]> IE7 及以下可識別 <![endif]--> <!--[if gte IE 7]> IE7 及以上可識別 <![endif]-->
背景。搜尋「.htaccess 緩存」可以找到大量設定教學。透過設定,可以把 CSS、JS 這類不常變動的檔案快取在使用者瀏覽器端,訪客再次造訪時直接讀取本地快取,不必再向伺服器請求,既加快開啟速度,也節省流量。
問題。快取有過期時間。在過期之前,瀏覽器只會讀本地快取。如果你已在伺服器上修改了 CSS 或 JS,回頭客的瀏覽器不會有任何變化,除非他們按 Ctrl + F5 強制重新整理,或手動清空快取。網站訪客成千上萬,你不可能要求每個人這麼做。
解法一:更改檔名。快取是以檔名為索引的,所以更新內容後換個檔名即可。
<link rel="stylesheet" href="https://www.example.com/style.css" type="text/css" media="screen" />
改成:
<link rel="stylesheet" href="https://www.example.com/index.css" type="text/css" media="screen" />
也可以把版本號寫進檔名:
<link rel="stylesheet" href="https://www.example.com/index.v2011.css" type="text/css" media="screen"/>
更新後只改版本號:
<link rel="stylesheet" href="https://www.example.com/index.v2012.css" type="text/css" media="screen"/>
解法二:加查詢參數。每次改檔名有點麻煩,那就直接在連結後面帶一個版本參數。
<link rel="stylesheet" href="https://www.example.com/style.css?v=2011" type="text/css" media="screen"/>
更新後改成 v=2012 即可:
<link rel="stylesheet" href="https://www.example.com/style.css?v=2012" type="text/css" media="screen"/>
小結。檔名後面的問號本身不產生實際作用,只是個後綴;但透過它可以帶上版本資訊,同時達到強制更新瀏覽器快取的效果。一個小細節,能省下大量溝通與排查成本。
補充:以上 UA 判斷與 CSS hack 屬於特定世代瀏覽器的產物,新專案應優先採用特徵偵測(feature detection)與標準語法。