在 Twitter 上看到 John Resig 的訊息,說 jQuery 不再使用 browser detecting 的技巧,完全改用 Object detecting:「They said it couldn't be done: jQuery no longer uses any browser/useragent sniffing! http://bit.ly/eXrP」
Browser detecting 在 ppk 的「Browser detect」這篇文章裡有提到,經常被用於 (且誤用於) 功能的判斷。比較好的方法是 Object detecting。
譬如說,目前 Firefox 3 支援 getElementsByClassName()
,但 Firefox 2 並不支援。如果你要使用這個功能,應該利用 object detecting 這樣寫:
if (document.getElementsByClassName) { // do something with getElementsByClassName } else { // use getElementsByTagName to emulate it }
而非用 browser detecting:
if (firefox3) { // do something with getElementsByClassName } else { // ... }
除了程式碼比較合理 (乾淨) 外,這樣寫出來的 code 也比較 future proofing。這點可以參考 John Resig 的「Future-Proofing JavaScript Libraries」。
如果我在之前自己定義了 getElementsByClassName 這個函數,那它還能正常的detect吗?
如果有被定義就用。