Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: document ready fires too early for my requirements

I am developing a site based all around photos. Some areas of this site require calculations based on image dimensions in order to work correctly. What i have found is that document ready is firing too early and my gui is behaving erratically as a result.

I removed the document ready function and replaced it with the good 'ol window.onload function, since, if i read correctly, this function does not fire until images are fully loaded.

My question is, will this cause any problems? And are there any other solutions that i have missed perhaps?

Thanks for the help guys!!

like image 488
user239237 Avatar asked Jan 09 '10 20:01

user239237


3 Answers

There is no reason you cannot use $(window).load() as opposed to $(document.ready(). You are correct about the function not firing until images are fully loaded (or failed to load).

The drawback of fully relying on $(window).load() are that in some cases it is readily apparent none of your javascript is working (i.e. navigation or click events) until every single item on your page has loaded. Some users, usually a website's power users, click through pages quite rapidly and this detracts from the overall user experience.

The happy medium would be to use $(window).ready() for most situations and only put events inside $(window).load() that absolutely require them.

like image 94
Corey Ballou Avatar answered Dec 09 '22 20:12

Corey Ballou


Try this instead:

$(window).load(function() {
 alert("images are loaded!");
});

See this link for a comparison of $(document).ready() and $(window).load()

http://4loc.wordpress.com/2009/04/28/documentready-vs-windowload/

like image 44
JCasso Avatar answered Dec 09 '22 21:12

JCasso


Altough window.onload would suit your needs, I'd recommend speeding up the things a bit:

$("img.load").load(function(){
    alert($(this).width());
});

Now you can process image individually as quickly as it is loaded and not waiting for the whole set of elements.

like image 31
metrobalderas Avatar answered Dec 09 '22 21:12

metrobalderas