Jackie Jackie - 6 months ago 73
Javascript Question

properly bind javascript events

I am looking for the most proper and efficient way to bind javascript events; particularly the onload event (I would like the event to occur after both the page AND all elements such as images are loaded). I know there are simple ways to do this in jQuery but I would like the more efficient raw javascript method.


There are two different ways to do it. Only one will work; which one depends on the browser. Here's a utility method that uses both:

function bindEvent(element, type, handler) {
   if(element.addEventListener) {
      element.addEventListener(type, handler, false);
   } else {
      element.attachEvent('on'+type, handler);

In your case:

bindEvent(window, 'load', function() {
    // all elements such as images are loaded here