Document.ready clarification? - javascript

I lately saw some sites which uses this pattern :
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
$(function (){...do some stuff with plugins...});
</script>
</head>
<body>
<script src="myplugin1.js"></script>
<script src="myplugin2.js"></script>
<script src="myplugin3.js"></script>
</body>
</html>
This made me think of some traps :
Question #1
document.ready event is raised not executed after the plugins(JS) has been parsed.
it is executed when the dom structure is done. (notice: I didn't say :"when all resources has been downloaded" !)
So there could be a situation where the document. readyfunction will try to use a plugin variable which hasn't been fully downloaded. (which will cause error).
Am I right ?
Question #2
This leads me to : "never use document.ready" before the script references location ( I mean : in situations where document.ready is dependent on those script variables).
Am I right ?
p.s. Im not talking about window.load which will obviously will work here but i'll have to wait much longer.

If you think about all the kinds of resources in a page, many can be loaded separately from the page content: images and stylesheets, for example. They may change the look of the page, but they can't really change the structure, so it's safe to load them separately.
Scripts, on the other hand, have this little thing called document.write that can throw a wrench into the works. If I have some HTML like this:
Who would <script>document.write("<em>");</script>ever</em> write like this?
Then browsers will parse it just fine; document.write, if used at the top level like that, effectively inserts HTML at that position to be parsed. That means that the whole rest of the page depends upon a script element, so the browser can't really move on with the document until that script has loaded.
Because scripts can potentially modify the HTML and change the structure, the browser can't wait to load them later: it has to load them at that moment, and it can't say the DOM is ready yet because a script might modify it. Therefore, the browser must delay the DOM ready event until all the scripts have run. This makes it safe for you to put the dependent code at the top in a ready handler.
However, I'd recommend you don't, because it's not very clear.

The event that $(document).ready equates to is DOMContentLoaded in modern browsers (and it falls back to some others in legacy browsers that equate to the same scenario).
MDN summarizes it pretty nicely:
The DOMContentLoaded event is fired when the document has been
completely loaded and parsed, without waiting for stylesheets, images,
and subframes to finish loading (the load event can be used to detect
a fully-loaded page).
So your scripts will always be parsed by the time it is executed.

Related

Where to place $(document).ready(function()? [duplicate]

This question already has answers here:
document.ready inside body tag
(2 answers)
Closed 9 years ago.
We often read here and there, that we must place our js code either on the page head section or before (sorry) the end body tag. Discussions about this aside, I'm just looking to know what are the reading order for such things by the browsers (taking that they do act as equals here):
Can we place:
$(document).ready(function(){
No matter where on the page structure, because we are using $(document).ready or should we still place it on the head section ?
Can anyone please clarify this.
If my question isn't clear, I can rephrase.
You can place a script anywhere in the document. Best practice usually advises placing scripts in the footer for page load performance concerns. Further, best practice usually advises placing the scripts together for ease of maintenance.
However, per the spec, there is no restriction on where in the document you place a script tag. You may place them together in the header, at the bottom of the body, sprinkled all over the document, or any combination thereof.
The use of the jQuery construct $(document).ready has the same result regardless of where it is placed within the document. The key is to understand the functionality behind this construct:
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.
So, ready is similar to document.onload, but not the same. It doesn't matter where the code is, if you execute it when document.onload is fired or when jQuery fires ready. Code's placement in a document is only significant if it is NOT wrapped by some event handler/listener.
The only restriction on the location on $(document).ready is that it cannot happen before you include the jQuery library. $(document).ready is using jQuery, so if jQuery doesn't exist.... you can't use it.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script>
alert('executed as soon as it is reached (as the document is downloaded)');
$(document).ready(function () { alert('on jQuery ready'); });
</script>
</head>
<body onload="alert('executed on document.onload event');">
<script>
alert('executed as soon as it is reached (as the document is downloaded)');
$(document).ready(function () { alert('on jQuery ready'); });
</script>
</body>
</html>
Documentation
SCRIPT specification at W3 - http://www.w3.org/TR/html401/interact/scripts.html
script (html 5) specification at W3 - http://www.w3.org/TR/html-markup/script.html
Placing Javascript in your pages at quirksmode - http://www.quirksmode.org/js/placejs.html
Jquery ready - http://api.jquery.com/ready/
AFAIK, $(document).ready event gets raised after DOM is completely loaded so it doesn't matter where you place it.
But they say to write the script at end of the body because page will show up to the end user instantly and javascript will continue to run as background process.
The browser executes the script from the top to the bottom, so the srcipt in the head section will execute before the script in the body. I prefer to put the script undernith the html code, but generally it desn't matter much if you vait for the page to fuly load.
The document ready function will wait until the DOM is loaded before running. So technically it doesn't matter where you put it. Many people like putting script in the head, because it makes sure the script is read before the page is loaded. Other people like putting it at the very end (just before the end body tag) so that all of the elements of the page are loaded before the script reads them. But since you're waiting for the DOM to load anyway, it doesn't matter.
If you have a small function, then I would just put the document ready function in the head tags.
As far as i know, the BKM is to place it in the footer (although mostly developers tend to place it in the head tag).
Main reason - most of the document DOM is rendered to the browser prior to loading JS.

JavaScript - head, body or jQuery?

This question is just to clear some things up. Some things like this have been asked before, and this rounds them all up into one question - where should JavaScript go in the HTML document, or, more importantly, does it matter? So, one of the things I'm asking is, does
<head>
<script type="text/javascript">
alert("Hello world!");
</script>
</head>
at all differ (in terms of functionality) from
<body>
<!-- Code goes here -->
<script type="text/javascript">
alert("Hello world!");
</script>
</body>
More importantly, I want to focus on JS that modifies or uses elements from the DOM in any way. So I know that if you put something like document.getElementById("test").innerHTML = "Hello world!" before <element id="test"></element> in your body, then it won't work since the body is loaded from top to bottom, making the JS load first, which will then proceed to try to manipulate an element that doesn't exist yet. So it should, just like the above, either go in the <head> or just before the </body> tag. The question is, aside from organisation and sorting, does it matter which one of these is chosen, and if so, in what way?
Of course, there is also a third method - the jQuery way:
$(document).ready(function(){ /*Code goes here*/ });
That way, it doesn't matter where in the body you place the code, since it will only be executed when everything has loaded. The question here is, is it worth importing a huge JS library just to use a method the need for which could be replaced with an accurate placing of your scripts? I'd just like to clear things up a little here, if you would like to answer, go ahead! Summary: where should different kinds of scripts go - head or body, and/or does it matter? Is jQuery worth it just for the ready event?
Most recommended method is to put it before </body> tag. Yahoo performance article also suggests that other than YSlow and Page Speed addons by Yahoo and Google respectively.
Quoting from Yahoo article linked above:
The problem caused by scripts is that they block parallel downloads.
The HTTP/1.1 specification suggests that browsers download no more
than two components in parallel per hostname. If you serve your images
from multiple hostnames, you can get more than two downloads to occur
in parallel. While a script is downloading, however, the browser won't
start any other downloads, even on different hostnames.
When you put scripts in <head> tag, the browsers goes for them thereby keeping other stuff on hold until scripts are loaded which users will perceive like slow loading of the page. This is why you should put scripts at the bottom.
As for:
$(document).ready(function(){/*Code goes here*/});
It is fired when DOM is available and ready to be manipulated. If you put your code at the end, you won't necessarily need this but usually this is needed because you want to do something as soon as DOM is available for use.
Although common practice, putting script tags in the head is not usually a good idea, as it holds up the rendering of your page until those scripts have been downloaded and processed (barring your use of async or defer and the browser supporting them).
The usual recommendation is to put script tags at the very end of the body tag, e.g., just before </body>. That way, all of the DOM elements above the script will be accessible (see links below). One caveat on that is that there can be a brief moment when your page has been at least partially-rendered but your scripts not processed (yet), and if the user starts interacting with the page, they may do something to raise an event that your script hasn't had time to hook yet. So you need to be aware of that. This is one reason for progressive enhancement, which is the idea that the page will work without JavaScript, but work better with it. If you're doing a page/app that just won't work without JavaScript at all, you might include some inline script at the top of the body tag (e.g., <script>minimal code here</script>) that hooks any bubbling events on document.body and either queues them for action when your script is loaded, or just asks the user to wait.
Using features like jQuery's ready is fine, but not really necessary outside of libraries (e.g., if you're in control of where the script tags will be, you don't usually need to use it; but if you're writing a jQuery plug-in that needs to do something on load [which is relatively rare, normally they just wait to be called], you usually do).
More reading:
YUI Best Practices for Speeding Up your Website
Google on when the DOM will be ready
It is possible to download javascripts in parallel by doing something like this:
(function () {
var ele = document.createElement('script');
ele.src = "https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js";
ele.id = "JQuery";
ele.onload = function () {
//code to be executed when the document has been loaded
};
document.getElementsByTagName('head')[0].appendChild(ele);
})();
In the example it downloads minified JQuery v1.7.2 from Google, this is a good way to download JQuery since downloading it from Google is like using a CDN and if the user has been on a page that used the same file it might be cached and therefor doesn't need to be downloaded
There is a really good Google tech talk about this here http://www.youtube.com/watch?v=52gL93S3usU&feature=plcp

Is placing script tag before </body> tag equivalent to jQuery's document.ready method

If we call a javascript method myMethod() in a script tag which is before closing body, is it equivalent to calling myMethod() inside jQuery's document.ready function ? If not, Why ?
From here:
Under the hood: $(document).ready() As you would expect from John
Resig, jQuery’s method for determining when the DOM is ready uses an
assortment of optimizations. For example, if a browser supports the
DOMContentLoaded event (as many non-IE browsers do), then it will fire
on that event. However, IE can’t safely fire until the document’s
readyState reaches “complete”, which is typically later. If none of
those optimizations are available, window.onload will trigger the
event.
These events are independent of a location within the HTML tag, as other event still are going on even at the time of rendering </body>.
No it's not the same, you place the <script> tags before the closing </body> tag to avoid blocking the rendering of html on older browsers, AFAIK, but you have no guarantee that the DOM is "ready"
Not exactly. $(document).ready(); reacts on the so called DOMContentLoaded event which is fired right after the DOM has been loaded and the browser is aware of all the elements on the page (not the content itself).
The main reason why code is usually put inside these blocks is not that much related to preventing blocking of parallel loading but to ensure that the elements which are to be manipulated during page load are actually loaded and present in the DOM tree. Not much sense in manipulating elements which the browser is not aware of right?
Putting JavaScript content (or any other content for that matter) at the bottom of the page is actually more closely related to the onload event which is fired after the page has finished loading, including the content itself. Either way its almost certain that content inside $(document).ready() blocks will be executed before the one at the bottom of the page however if you load external libraries on which the code inside the ready() block relies you can't put those at the bottom of the page.
In general if you have code that isn't dependent on external libraries and a successful loading of DOM you can safely put it at the bottom of the page. If you however have stuff that needs to be executed right after the DOM has been loaded you most definitely want that code in the $(document).ready() block, but do have in mind that you can place that block wherever you want, even in the middle of the page (which can be a nice trick sometimes).

If I keep JavaScript at bottom or keep JavaScript in <head> inside document.ready, are both same thing?

If I keep JavaScript code at bottom or keep JavaScript code in <head> inside document.ready, are both same thing?
I'm confused between these two methodologies, http://api.jquery.com/ready/ and http://developer.yahoo.com/performance/rules.html#js_bottom.
Is there any benefit to putting JavaScript code at bottom (just before </body>) even if I keep the code inside.
$(document).ready(function() {
// code here
});
As JavaScript is attached in
<head>
<script type="text/javascript" src="example.js"></script>
</head>
In General, your should put your Javascript files at the bottom of your HTML file.
That is even more important if you're using "classical" <script> tag files. Most browsers (even modern ones) will block the UI thread and therefore the render process of your HTML markup while loading & executing javascript.
That in turn means, if you're loading a decent amount of Javascript at the top of your page, the user will expire a "slow" loading of your page, because he will see your whole markup after all your script has been loaded and executed.
To make this problem even worse, most browsers will not download javascript files in a parallel mode. If you have a something like this:
<script type="javascript" src="/path/file1.js"></script>
<script type="javascript" src="/path/file2.js"></script>
<script type="javascript" src="/path/file3.js"></script>
your browser will
load file1.js
execute file1.js
load file2.js
execute file2.js
load file3.js
execute file3.js
and while doing so, both the UI thread and the rendering process are blocked.
Some browsers like Chrome finally started to load script files in parallel mode which makes that whole problem a little bit less of an issue.
Another way to "workaround" that problem is to use dynamic script tag insertion. Which basically means you only load one javascript file over a <script> tag. This (loader) script then dynamically creates <script> tags and inserts them into your markup. That works asyncronously and is way better (in terms of performance).
They will load all the same in terms of you being able to access the code.
The differences are in the perceived speed of loading of the page. If the javascript is last it will not block any CSS that is trying to be downloaded, which should always be at the top, and will not block any images that need to be downloaded.
Browsers only ask for items as they find them in the HTML but they only have a limited amount of download streams (~10 in modern browsers) so if you doing a lot of requests for images/css and for JS something is going to lose and the perceived speed/ user experience of the page load of your page will take a hit.
They are not the same thing as the ready event is fired when the DOM tree has been built, while scripts at the end of the page may actually execute afterward.
Either way, they're both safe entry points for your app's execution.
The Yahoo! Developer site is saying that if you put JavaScript at the bottom of the page, it won't block loading of other resources by the browser. This will make the page's initial load quicker.
jQuery is specifying a function to load when the entire page has loaded.
If you have a function which executes on page load, it won't matter whether you include it in <head> or at the bottom of the page, it will be executed at the same time.
It's important to consider what the JavaScript is actually doing on your page when deciding where to put it. In most cases, the time it takes to load and run JavaScript makes placing it at the end of the page more logical. However, if the page rendering itself depends on Ajax calls or similar, this might not be the case.
Here's a good read on the subject of document.ready() not being appropriate for all JS.
Position of <script> tag don't involve your script if you use document.ready.
It seems JavaScript is charged faster when placed before </body> but I'm not sure.
Even with the script at the bottom of the HTML document, the DOM may not be fully loaded. All closed elements above the script will typically be ready, a DOM ready event may be necessary in corner cases.

Does it matter where JavaScript is placed on a html page?

I've messing about with html5, I've never really had a good look at JavaScript before.
I'm referencing script file like this (not in the head)
<script src="somthing.js"></script>
However the script only seems to work if it placed below certain elements on the page.
Are there particular situations when it matters where javascript is placed?
Thanks in advance.
If the script isn't waiting for an onload or "ready" event of some sort, it needs to be place after the elements it references (otherwise they won't be there to find). If you're unsure, stick it just before </body>.
In this case it looks like that's exactly what's happening, it's looking for elements that haven't been added to the DOM yet. Placing the script at the bottom of the <body> is one common practice to counter this. Some alternatives are using the window.onload event to run your code, or jQuery's $(document).ready() for example (most major libraries have some equivalent of this).
If your script is acting on an element it needs to either be placed after that element on the page or set up to execute when the page is finished loading. If the script runs before the element has been added to the DOM (which occurs when it is encountered as the browser parses the page), then the script can't find the element upon which you want it to act. Placing the script after the element ensures that the element is available for it to work on. Likewise, forcing it to run after the entire page loads makes sure that all elements are available to the script.
I'd suggest that, in so far as possible, you load your scripts right before the closing </body> tag. I would also look at using a framework, like jQuery, which makes it easy to run your scripts on page load complete and wrap the code inside it's load event.
The best practice according to Yahoo's Performance Rules is to place scripts at the bottom of the page:
The problem caused by scripts is that they block parallel downloads. The HTTP/1.1 specification suggests that browsers download no more than two components in parallel per hostname. If you serve your images from multiple hostnames, you can get more than two downloads to occur in parallel. While a script is downloading, however, the browser won't start any other downloads, even on different hostnames.
In some situations it's not easy to move scripts to the bottom. If, for example, the script uses document.write to insert part of the page's content, it can't be moved lower in the page. There might also be scoping issues. In many cases, there are ways to workaround these situations.
An alternative suggestion that often comes up is to use deferred scripts. The DEFER attribute indicates that the script does not contain document.write, and is a clue to browsers that they can continue rendering. Unfortunately, Firefox doesn't support the DEFER attribute. In Internet Explorer, the script may be deferred, but not as much as desired. If a script can be deferred, it can also be moved to the bottom of the page. That will make your web pages load faster.
Well we'd need to know what was in your script to tell you really, but the short answer is "yes it does matter".
Scripts (essentially) execute when encountered by the browser. A classic blunder is to make a reference to a page element in a script placed earlier in the document than the element it references - when the script is executed the element doesn't exist yet!
It is generally considered appropriate to keep scripts in the head, the solution to the above problem therefore being to attach functional code to onload event handlers.
Bonus round: a much more subtle reason script placement matters is because most browsers will single-thread downloads when they encounter a script (for security reasons and because the script can modify the download requirements for example). This is one of the reasons yahoo recommends placing scripts last in your document, but it's a controversial thing to do for a subtle benefit of perception only.
YES it does.
for example, let's just say your js code is at the top. and it is interpreted before the browser is done setting up a section of the dom tree...in this case the HTML element that you are referencing, if referenced before it is available, will produce an error saying that the element is undefined.
Another reason is the user experience. If the css is at the top, when the html is displayed all looks good, but unless the js is at the bottom, you will have to wait for it to be loaded and be ready for execution before the rest is rendered; therefore, slowing down the rate at which items on the screen are rendered.
I see it a lot. Different strokes for different browsers, but just put the js at the bottom, and css at the top and you avoid having to worry about stuff like this.
It depends on what the script is designed to do. If it is using the document.write() method, then it does matter where it is on the page. If it's trying to reference elements in the DOM, it is best put in the HEAD and have those functions that access DOM elements triggered after the page is loaded.
There are a couple of scenarios where the placement is important.
Assuming you have a function call foo() in your_script.js and you call it before you include your_script.js, than it simply won't work because foo() isn't defined yet.
If the code requires a certain element to be available (for example, a lightbox script) than it is possible that loading the code before your lightbox image elements results in the lightbox not doing anything.
So basically... it depends very much on what scripts you are running. Sometimes it will matter, other times it won't.
Yahoo actually recommends putting your scripts at the bottom. The downloading of a JS file is a blocking action which means nothing else is downloading at that time (such as images/css) By putting your scripts at the bottom the user gets the html/images/css first and actually see the page faster, and your JS downloads after to add interactivity.
Having said that, as the other posts mention, your script has to wait until the dom is ready before actually doing anything to the DOM, otherwise you'll have varied behaviour depending on when the DOM is ready.
Well, here is what I think.
If you need to execute your script, before the HTML starts the render in the clients browser then it will be better to be placed in <head> section.
And if you are executing a JavaScript code which communicates with a element in some way then the script should be placed behind that element, because if the script starts ahead then it can't find its respective element to communicate with. So it is better to placed behind element.
This is not only about where the script is placed in the page, but also when the code in the script is executed.
Script tags normally goes in the head section of the page. However, that means that no elements are loaded when the code loads, and if it executed immediately you can't access any elements. The solution to that is to use the onload event of the page. Example:
<html>
<head>
<title></title>
<script>
function init() {
document.getElementById('message').innerHTML = 'Hello world!';
}
</script>
</head>
<body onload="init();">
<div id="message"></id>
</body>
</html>
Javascript libraries may have other methods of doing something similiar, like the ready event in jQuery.
You can place scripts in the page (although this is not what's recommended by the HTML standard), but if you need to access elements in the page from code that runs immediately, the script has to be loaded after the elements. Example:
<html>
<head>
<title></title>
</head>
<body>
<div id="message"></id>
<script>
document.getElementById('message').innerHTML = 'Hello world!';
</script>
</body>
</html>
Scripts may also be placed late in the page for performance reasons. You can keep that in mind and save it until you actally have any performance problems.
In simple terms : Make sure the element(s) the script accesses is loaded before the script starts executes. Ofcourse if you are unsure put it just before .
Your script likely attempts to operate on the DOM before it is ready. This should not be solved by moving it around, but rather by deferring execution with domready callbacks.
After that is sorted, you should aspire to keep script inside of head. It used to be a common practice to include scripts at the bottom of the page to avoid page- and request-blocking. In HTML5 such performance impacts no longer matter since you can take advantage of async attribute. It allows for the loading of JS files to be initiated without side-effects:
Traditional scripts block the HTML parser, preventing the rest of the page from being rendered until the script has been downloaded and run. Scripts using HTML5 async unblock the rest of the page so it can continue loading while the script is being downloaded. ^

Categories