Welcome to the first of what I hope will be a regular series of JavaScript tips. :-)Object detection is common in JavaScript. Browser irregularities mean that your code must sometimes contain branches for different browsers. Here is a simple way to speed up object detection for a leaner and meaner script.Instead of this:
function addEvent(element, type, handler) {  if (element.addEventListener) {    element.addEventListener(type, handler, false);  } else if (element.attachEvent) {    element.attachEvent("on" + type, handler);  }};

Do this:

var addEvent;if (document.addEventListener) {  addEvent = function(element, type, handler) {    element.addEventListener(type, handler, false);  };} else if (document.attachEvent) {  addEvent = function(element, type, handler) {    element.attachEvent("on" + type, handler);  };} else {  addEvent = new Function; // not supported}

This means you are only performing object detection once instead of every time you call addEvent. Obviously, this technique can be applied to any function where you are performing object detection.


Related Posts

« »