# Add event listener when window loads

I've been using this code for quite some time, but am wondering if there's any improvements I can make to it. Basically it's just code that runs when the page loads or if the code is run after page load, it will run right away. Do you see any cross browser compatibility issues or any more efficient ways of writing this? ol() is a predefined function to be run.

(document.readyState=='complete') ?
ol():(window.addEventListener&&window.addEventListener("load",ol,false)||
window.attachEvent&&window.attachEvent("onload",ol));

-

## migrated from meta.codereview.stackexchange.comFeb 26 '13 at 3:56

This question came from our discussion, support, and feature requests site for peer programmer code reviews.

I suggest you take a look at jQuery's implementation of .ready() – Joseph the Dreamer Feb 26 '13 at 8:28
There's some good coverage in Paul Irish's paulirish.com/2010/10-things-i-learned-from-the-jquery-source .ready coverage starts around 21:20. There's also some links to jQuery sources. – Michael Paulukonis Feb 26 '13 at 15:47

## 1 Answer

Just for dealing with ready alone I use jQuery -- it does the cross-browser heavy lifting, is well-tested and maintained. Minified, it's only 32K, and included from a CDN, you get fast delivery that may already be cached in your user's browser.

And there is a lot more code than what you have above to deal with all of the browsers being ready.

There's some good coverage in Paul Irish's 10 Things I learned from the jQuery source screen-case .ready coverage starts around 21:20. There's also some links to jQuery sources.

-
using jQuery only for the ready event is to heavy.. – Wouter J Feb 26 '13 at 16:02
If you're not using a CDN, quite possibly. 32K is HUUUUGE. On my 300 baud modem it takes nearly a minute and a half to download. But the code above is nowhere near heavy enough. extract what you need from JQ, and credit it. I'd be surprised if you don't have other uses for it. – Michael Paulukonis Feb 26 '13 at 16:25