views:

16

answers:

1

Hello, with Javascript, I'm wondering what's the current best way to load my code onto the page (without jQuery) after the rest of the page has been loaded. So like a window.onload...

I was looking at several options but they all seem outdated and not-completely cross-browser friendly.

Does this look like it would be best? It does work, I got it from online tools but I think it spawned from Scott Andrews

 function addEvent(obj, evType, fn) { 
 if (obj.addEventListener){ 
   obj.addEventListener(evType, fn, false); 
   return true; 
 } else if (obj.attachEvent){ 
   var r = obj.attachEvent("on"+evType, fn); 
   return r; 
 } else { 
   return false; 
 } 
}

function init () {
// do something
}

addEvent(window, 'load', init); 

Even though it works and passes all my tests and seems quite flexible, I'm a little worried about this approach, because

1) I don't fully understand it

2) It seems old, scott andrews page is from 2001!

3) Opera Technical support didn't like it, see "The voice of Opera" on online tools

Is this the best way to do this?

+1  A: 

From The Javascript Source

/* This script and many more are available free online at
The JavaScript Source!! http://javascript.internet.com
Created by: Caleb Duke | http://www.askapache.com/ */

//------------------------------------
// heavily based on the Quirksmode addEvent contest winner, John Resig
// addEvent
function addEvent(obj,type,fn){
    if(obj.addEventListener) obj.addEventListener(type,fn,false);
    else if(obj.attachEvent){
        obj["e"+type+fn]=fn;
        obj[type+fn]=function(){obj["e"+type+fn](window.event);}
        obj.attachEvent("on"+type,obj[type+fn]);
    }
}

//------------------------------------
// removeEvent
function removeEvent(obj,type,fn){
  if(obj.removeEventListener) obj.removeEventListener(type,fn,false);
  else if(obj.detachEvent){
    obj.detachEvent("on"+type,obj[type+fn]);
    obj[type+fn]=null;
    obj["e"+type+fn]=null;
  }
}
Saul
Thank you! That's really quite nice, I like it alot. I am curious, however, do I need to utilize removeEvent at all, to keep from leaving an open event in memory or something? What function would I pass to removeEvent? I can't pass the one I just loaded that seems to break stuff.
yekta
You need to remove the event only if you want to get rid of the behavior that element has. So in general, you don't have to. The memory usually gets cleared after the browser leaves the page. PS. You might want to accept answers on your questions, that way you'll get more views on the next question.
Saul
Thanks :) Still getting used to Stack Overflow.
yekta