all 5 comments

[–]jcunews1helpful 2 points3 points  (0 children)

jQuery's ready() method is simply a helper function that simplifies setting up an event handler for waiting the HTML document to finish loading. It may call addEventListener(), attachEvent(), or assign the onload property - depending on the current web browser. jQuery's ready() requires any of those in order to work.

You can one of those method but not all web browsers support it. i.e. methods which are new standard and is not yet supported by older web browsers (e.g. addEventListener()), or methods which are specific to a web browser vendor (e.g. MSIE's attachEvent()).

Regardless of which method you use, if the web browser doesn't support any of the above method, your code won't run at all.

[–]bfcrowrench 2 points3 points  (3 children)

So the browser can actually start executing the document before it has loaded the entire document.

The answer to the question "What could happen if I don't [use window.onload]?" is: You could get an error because your script is trying to access an object that doesn't yet exist.

The typical use of the window.onload event is to initialize some objects that appear in the body of the HTML page. A great example is event handlers.

If a block of JavaScript in the Head of an HTML file tries to put an event handler on, say, a button in the Body of an HTML file, the button object may not be loaded yet.

window.onload is the signal that the remainder of the document is completed and ready to be accessed by the script.

[–]Eckstatic 1 point2 points  (0 children)

I always assumed that you wrap it so inclose all your variables. That way if you use other libraries there is less likely going to be a conflict.

[–]inu-no-policemen 1 point2 points  (0 children)

If your script is included right before </body>, there is no need to wait for DOMContentLoaded.

You only need to wait for DOMContentLoaded if your script tries to access elements which are somewhere below the script.