$(Document).Ready(Function(){}); VS Script at the Bottom of Page

$(document).ready(function(){}); vs script at the bottom of page

Very little in and of itself, either way the DOM will be ready for you to operate on (I was nervous about that until I read this from Google). If you use the end of page trick, your code may get called the slightest, slightest bit sooner, but nothing that will matter. But more importantly, this choice relates to where you link your JavaScript into the page.

If you include your script tag in the head and rely on ready, the browser encounters your script tag before it displays anything to the user. In the normal course of events, the browser comes to a screeching halt and goes and downloads your script, fires up the JavaScript interpreter, and hands the script to it, then waits while the interpreter processes the script (and then jQuery watches in various ways for the DOM to be ready). (I say "in the normal course of things" because some browsers support the async or defer attributes on script tags.)

If you include your script tag at the end of the body element, the browser doesn't do all of that until your page is largely already displayed to the user. This improves perceived load time for your page.

So to get the best perceived load time, put your script at the bottom of the page. (This is also the guideline from the Yahoo folks.) And if you're going to do that, then there's no need to use ready, though of course you could if you liked.

There's a price for that, though: You need to be sure that the things the user can see are ready to be interacted with. By moving the download time to after the page is largely displayed, you increase the possibility of the user starting to interact with the page before your script is loaded. That's one of the counter-arguments to putting the script tag at the end. Frequently it's not an issue, but you have to look at your page to see whether it is and, if so, how you want to deal with it. (You can put a small inline script element in the head that sets up a document-wide event handler to cope with this. That way, you get the improved load time but if they try to do something too early, you can either tell them that or, better, queue the thing they wanted to do and do it when your full script is ready.)

What's the difference between $(document).ready() and just omit it?

<script> tags in your HTML that do not have the defer or async attributes will execute in the order the HTML document is parsed from top down. That means that a script near the top of the document will execute before the rest of the document has been parsed and thus before it is available. This makes the placement of a script or the execution timing of a script relevant in many cases.

In controlling this execution timing, you have at least five choices for executing startup scripts:

  1. You can put the script in the <head> section or the top of the <body> section and execute it as it loads. This has the disadvantage that the DOM is not yet loaded so you can't operate on elements within the page.

  2. You can insert the script right before the </body> tag and all of the DOM will be loaded and your script will be able to access everything.

  3. You can insert your script anywhere you want (including in the <head> tag) and use $(document).ready(fn) to not execute the fn until the DOM is ready. Internally, jQuery listens for the DOMContentLoaded event and when it fires, it executes any .ready() handlers.

  4. You can insert your script anywhere you want (including in the <head> tag) and use window.onload(fn) to not execute the fn until the DOM is ready and all external resources such as images have loaded. Note, you can also use the jQuery version $(window).load(fn).

  5. You can use the async or defer attributes on the script tag to force it to load asynchronously and somewhat later. This will create an indeterminate time of script execution (though always later than if it was just inline) so you will likely need some specific control like $(document).ready() to know that the DOM is safe before your script executes. You can see these other questions/answers Script Tag - async & defer and Load and Execute order of scripts for a lot more details on the operation of the async and defer attributes.

So, if you carefully place your script tag in the right place or your startup script does not try to access DOM elements, you don't need to use either $(document).ready(fn) or window.onload(fn).

But, if you don't entirely control where the script is placed and you need to access DOM elements or you want your script to be able to be placed anywhere and still have it do the right thing or if you just want all your scripts in the <head> tag, then you will need to delay the execution of your script until the DOM is ready and either $(document).ready(fn) or window.onload(fn) will make it easy to do so.

jQuery: Why use document.ready if external JS at bottom of page?

Great question.

There is some confusion around the whole "put scripts at the bottom of your page" advice and what problem(s) it attempts to solve. For this question I am not going to talk about whether putting scripts at the bottom of the page affects performance/loadtimes or not. I am only going to talk about whether you need $(document).ready if you also put scripts at the bottom of the page.

I'm assuming you are referencing the DOM in those functions you are immediately invoking in your scripts (anything as simple as document or document.getElementById). I'm also assuming you are asking only about these [DOM-referencing] files. IOW, library scripts or scripts that your DOM-referencing code requires (like jQuery) need to be placed earlier in the page.

To answer your question: if you include your DOM-referencing scripts at the bottom of the page, No, you do not need $(document).ready.

Explanation: without the aid of "onload"-related implementations like $(document).ready the rule of thumb is: any code that interacts with DOM elements within the page should to be placed/included further down the page than the elements it references. The easiest thing to do is to place that code before the closing </body>. See here and here. It also works around IE's dreaded "Operation aborted" error.

Having said that, this by no means invalidates the use of $(document).ready. Referencing an object before it has been loaded is [one of] the most common mistakes made when beginning in DOM JavaScript (witnessed it too many times to count). It is jQuery's solution to the problem, and it doesn't require you to have to think about where this script will be included relative to the DOM elements it references. This is a huge win for developers. It's just one less thing they have to think about.

Also, it's often difficult or impractical to move all DOM-referencing scripts to the bottom of the page (for example any script that issues document.write calls have to stay put). Other times, you are using a framework that renders some template or creates pieces of dynamic javascript, within which references functions that need to be included before the js.

Finally, it used to be "best practice" to jam all DOM-referencing code into window.onload, however it has been eclipsed by $(document).ready implementations for well document reasons.

All this adds up to $(document).ready as a far superior, practical and general solution to the problem of referencing DOM elements too early.

What is the advantage of using jquery on ready instead call function

Only if you put the function at the very bottom of the page, there is no advantage. However, you usually want to have the choice to put code where you like it. $(document).ready() gives you this choice (actually the underlying javascript does).

Furthermore, for other programmers, it might not seem obvious that this function has to be executed right away when the page loads, and might therefor refactor the function somewhere else unknowingly. By using the document ready event, you're making your code more explicit i.e. saying "this piece of code needs to run as soon as the document has been loaded".

What's the difference between $(document).ready() and including a script at the end of the body?

JavaScript code inside the <script> tags is evaluated (executed) immediately. Note that in this case the page has not been parsed yet (entirely), and the DOM is not yet ready.

JavaScript code inside the jQuery ready() callback is evaluated on the DOMContentLoaded event, which occurs after the entire HTML source code has been parsed by the browser.

About this event: https://developer.mozilla.org/en/Gecko-Specific_DOM_Events

Note that the modern way of defining the ready handler is this:

$(function() {
// code
});

Also, check out this SO question, which points out what happens when you don't use the ready callback: How many JavaScript programs are executed for a single web-page in the browser?

Why is $(document).ready needed after the script tag?

$(document).ready is javascript code, so it has to be written in <script> element and after jQuery is loaded.

If you don't write $(document).ready, your code will not wait for DOM to load completely and execute the javascript code immediately.

If you're using script in <head> that is using/manipulating some elements from DOM, you'll need ready, otherwise you'll get null/undefined.
If you're using script at the end of <body>, then you'll be safe as all the elements are loaded.

Quoting as it is from jQuery Docs

While JavaScript provides the load event for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received. In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed. The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers and run other jQuery code. When using scripts that rely on the value of CSS style properties, it's important to reference external stylesheets or embed style elements before referencing the scripts.

In cases where code relies on loaded assets (for example, if the dimensions of an image are required), the code should be placed in a handler for the load event instead.

Example? Sure!

In Head no ready

<!DOCTYPE html><html lang="en">
<head> <meta charset="UTF-8"> <title>Document</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script> <script> alert($('#myname').val()); </script></head>
<body> <input type="text" value="Tushar" id="myname" /></body>
</html>

Is $(document).ready necessary if I put all my JavaScript at the bottom of the page?

This SO answer says NO:

stackoveflow question

$(document).ready is for assurance full DOM is available at the time the function is called.
Any functions and events not depending on the DOM don't need to be put into the ready event.

Also - to improve page rendering speed - load javascript files dynamically in non-blocking fashion: http://berklee.github.com/nbl/ or https://github.com/rgrove/lazyload/

This technique works somewhat like this:

 var script = document.createElement("script");
script.type = "text/javascript";
script.src = "file1.js";
document.getElementsByTagName("head")[0].appendChild(script);

This new element loads the source file file1.js. The file begins downloading as soon as the element is added to the page. The important thing about this technique is that the file is downloaded and executed without blocking other page processes, regardless of where the download is initiated. You can even place this code in the header of a document without affecting the rest of the page (aside from the one HTTP connection that is used to download the file).

this book: "High Performance JavaScript" by Nickolas Zakas has a lot of interesting information about JavaScript performace optimization.

What is the point of putting the $(document).ready function if the code is at the bottom?

Truth is that document.ready and bottom of document are pretty much the same thing, since by the end of document all controls are there. Personally I will still prefer document.ready since it's the way JQuery framework identifies document end (and ideally we should stick to framework's recommended ways) and secondly it will take care of anyone moving the code by mistake.

Best practices for placing the Document Ready function

The best practice is to put the code before you close </body> tag.

In this case you can get rid of "document ready" wrapper because the DOM will be already ready :)



Related Topics



Leave a reply



Submit