Dean
Dean

Reputation: 8998

Use Onload or ready?

In my application i am using

$(document).ready()

What is the difference between this and

$(document).onload()

Upvotes: 5

Views: 4783

Answers (4)

redsquare
redsquare

Reputation: 78687

All explained inside the jquery docs.

The first thing that most Javascript programmers end up doing is adding some code to their program, similar to this:

window.onload = function(){ alert("welcome"); }

Inside of which is the code that you want to run right when the page is loaded. Problematically, however, the Javascript code isn't run until all images are finished downloading (this includes banner ads). The reason for using window.onload in the first place is that the HTML 'document' isn't finished loading yet, when you first try to run your code.

To circumvent both problems, jQuery has a simple statement that checks the document and waits until it's ready to be manipulated, known as the ready event:

As an aside (and as suggested by yahoo) I always ensure my jquery/js scripts are included just before the body closing tag. That way you do not need to worry about window load or jquery ready functions.

Upvotes: 1

Sarfraz
Sarfraz

Reputation: 382919

The ready is triggered when only the DOM becomes ready while onload triggers when all resources of the page including DOM, images, frames, etc have loaded.

See:

$(document).ready vs. $(window).load

Note that ready lies with jQuery not raw javascript so I assume you know that and that way comparison seems logical.

Upvotes: 9

Dolph
Dolph

Reputation: 50720

.ready()

A function to execute after the DOM is ready.

-From the jQuery API Docs

.onload()

The onload event occurs when the user agent finishes loading a window or all frames within a FRAMESET.

-From the HTML 4.01 Specification

Upvotes: 2

Jason Miesionczek
Jason Miesionczek

Reputation: 14448

.ready() is called as soon as the page code is downloaded and parsed.

.onload() is called when all the images/videos/etc are downloaded.

Use .ready() for jQuery to work best, unless you have a specific reason for waiting until onload().

Upvotes: 7

Related Questions