Detecting support for a given JavaScript event?

耗尽温柔 提交于 2019-11-26 09:37:20

问题


I\'m interested in using the JavaScript hashchange event to monitor changes in the URL\'s fragment identifier. I\'m aware of Really Simple History and the jQuery plugins for this. However, I\'ve reached the conclusion that in my particular project it\'s not really worth the added overhead of another JS file.

What I would like to do instead is take the \"progressive enhancement\" route. That is, I want to test whether the hashchange event is supported by the visitor\'s browser, and write my code to use it if it\'s available, as an enhancement rather than a core feature. IE 8, Firefox 3.6, and Chrome 4.1.249 support it, and that accounts for about 20% of my site\'s traffic.

So, uh ... is there some way to test whether a browser supports a particular event?

Thanks.


回答1:


Well, the best approach is not going through browser sniffing, Juriy Zaytsev (@kangax) made a really useful method for detecting event support:

var isEventSupported = (function(){
  var TAGNAMES = {
    'select':'input','change':'input',
    'submit':'form','reset':'form',
    'error':'img','load':'img','abort':'img'
  }
  function isEventSupported(eventName) {
    var el = document.createElement(TAGNAMES[eventName] || 'div');
    eventName = 'on' + eventName;
    var isSupported = (eventName in el);
    if (!isSupported) {
      el.setAttribute(eventName, 'return;');
      isSupported = typeof el[eventName] == 'function';
    }
    el = null;
    return isSupported;
  }
  return isEventSupported;
})();

Usage:

if (isEventSupported('hashchange')) {
  //...
}

This technique is now used in some libraries like jQuery.

Read more here:

  • Detecting event support without browser sniffing



回答2:


The Mozilla documentation suggests the following:

if ("onhashchange" in window) {
    alert("The browser supports the hashchange event!");
}

This works in IE8 and the Chrome 5 beta too (I didn't test Chrome 4.1), and correctly fails in Opera and Safari.




回答3:


Here is a modification of the answer provided by CMS, which doesn't contain a function in another, which I think would work:

function event_exists(eventName){
    if(typeof(eventName)!='string' || eventName.length==0)return false;
    var TAGNAMES = {
        'select':'input','change':'input',
        'submit':'form','reset':'form',
        'error':'img','load':'img','abort':'img'
    }
    var el = document.createElement(TAGNAMES[eventName] || 'div');
    eventName = 'on' + eventName;
    var isSupported = (eventName in el);
    if (!isSupported) {
        el.setAttribute(eventName,'return;');
        isSupported = (typeof(el[eventName])=='function');
    }
    el = null;
    return isSupported;
}


来源:https://stackoverflow.com/questions/2877393/detecting-support-for-a-given-javascript-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!