[removed] The best way to detect IE

前端 未结 3 932
礼貌的吻别
礼貌的吻别 2021-01-13 12:22

Reading this article I\'ve found a following piece of code:

if (\'v\'==\'\\v\') { // Note: IE listens on document
    document.attachEvent(\'onstorage\', onS         


        
3条回答
  •  一生所求
    2021-01-13 13:14

    If you can avoid it, don't test for browsers. Do feature detection. This will mean that your code is (more likely to be) future-proof. In this case, for instance, if you discovered that the browser was IE and decided to use attachEvent because of it, you would miss out on the fact that addEventListener (superior) is available in IE9.

    In this case, test to see if document.addEventListener exists. If it does, you have the answer.

    if (document.addEventListener) {
        document.addEventListener(...);
    } else {
        document.attachEvent(...);
    }
    

    Edit: duri's comment above shows that this test fails in IE9 (as per standards), which actually means it is a perfect test for addEventListener, since that is available from IE9. However it is still far, far better to program for specific functionality, rather than specific browsers.

提交回复
热议问题