Use jquery before the DOM is ready?

Use jquery before the DOM is ready?

I'm trying to have jquery set an image's opacity to 0. Then, while the image is fully loaded, it will fade the image in.

It seems to work fine, unless the images have already been viewed in the browser and are stored in cache. In this case, the image is already loaded by the time of $(document).ready, then it fades out, then fades back in.

I'm doing it like this:
$(document).ready(function() {
   $("#mainimage").animate({opacity: "0"}, 0);
});


$(window).load(function() {
//when everything is finally loaded, fade image in

$("#mainimage").animate({opacity: "1"}, 1000);
});


I need to have the image opacity at 0 before document ready... how do I do this?