tags:

views:

40

answers:

1

How do I prevent my jQuery script from running until the whole page is loaded? (Including images .. ).

Thanks!

+4  A: 

Instead of $(document).ready(/* ... */); you can use:

$(window).load(
    function() {

});

Or you could just put a script block at the bottom of the page, so by the time the scripts are reached the rest of the DOM's loaded already.

David Thomas
but this doesn't mean every image has been loaded.just the dom.
Sven Klouem
In general, it is advantageous to put your scripts at the bottom if you don't need them to execute until after the page has loaded. By doing this browser doesn't need to interpret the JavaScript earlier and it lets the rest of the page load faster
Matthew Manela
@Sven, putting scripts at the bottom of the page *increases* the chance of the page being ready. There's no reason you can't use both techniques at the same time. Personally I always default to using `$(document).ready(/*...*/);` for whatever reason, and putting it in the `head` just because...well. Habit, I think. Though if I'm working on anything involving images in the scripts *then* I'll put a `$(window).load(/*...*/)` at the bottom instead. And marvel that I don't do that way *every* time... =/
David Thomas
ok thx, but is there no way to ensure everything has loaded?
Sven Klouem
Yeah, so far as I've ever been able to tell that's precisely what `$(window).load(/*...*/)` **does**: (reference for the [load event](http://api.jquery.com/load-event/) at api.jquery.com), the example near the bottom of the page states: [`$(window).load()`] "[runs] a function when the page is fully loaded including graphics."
David Thomas
thx for your help ;) #
Sven Klouem
@Sven: no worries, it's always a pleasure; Was I able to help solve your problem?
David Thomas