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

what is the difference / advantage / disadvantage of writing script at the bottom of the page and writing the script in
$(document).ready(function(){});

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.)

Your page will load slower by scattering $(document).ready() scripts throughout the DOM (instead of all at the end) because it requires jQuery to be synchronously loaded first.
$ = jQuery. So you can't use $ in your scripts without first loading jQuery. This approach forces you to load jQuery near the beginning of the page, which will halt your page load until jQuery is fully downloaded.
You cannot async load jQuery either because in many cases, your $(document).ready() script(s) will try to execute before jQuery is fully async loaded and cause an error, because again, $ isn't defined yet.
That being said, there is a way to fool the system. Essentially setting $ equal to a function that pushes $(document).ready() functions into a queue/array. Then at the bottom of the page, load jQuery then iterate through the queue and execute each $(document).ready() one at a time. This allows you to defer jQuery to the bottom of the page but still use $ above it in the DOM. I personally haven't tested how well this works, but the theory is sound. The idea has been around for a while but I've very, very rarely seen it implemented. But it seems like a great idea:
http://samsaffron.com/archive/2012/02/17/stop-paying-your-jquery-tax

Related

Will placing the <script> tags after </body>, but before </html>, speed up the page performance?

I have read a StackOverflow answer here, as it says:
Also, place the <script> tags at the bottom of the page, even after
</body>, but before </html>. This will load the scripts last and load
the ads last.
Is it real? Why it would work?
Loading a "classic" script is synchronous by default. This means that when the script tag is encountered, the HTML parser will wait for this script to be downloaded and executed before it is able to continue parsing what follows.
So, yes, putting your script at the end of the markup will allow the parser to have gathered enough DOM information and stylesheets and everything before it gets blocked fetching that script.
The renderer may even be able to pre-render the page while this script is being fetched, making it looks like the page did load faster.
But no, placing it after the tag won't make anything "speed up" in comparison to placing it before. This will just create an error in the parser, which will have to move it back inside the <body>, and it will make your page fail to pass validators. (Though to be fair, this was not the claim made in that quote).
Also, note that just doing this that way will still block the parser synchronously, and thus, all the asynchronous tasks that should happen at the end of the parsing will still get delayed.
So the best if you want to load a script that doesn't need to execute synchronously is to load it with the async attribute.
The purpose of adding at bottom of the page is, controlling the compile-time errors.
Consider the scenario, we have written some addClass() functionality to an ID element, if we include this in top it can't find out the Id element.
So we are adding it to the bottom of the page, once the DOM has been loaded.
TL:DR; faster? No, not really. The impression of loading faster? Yes.
When the browser is rendering the DOM and it comes across a <script> tag, it must halt, execute the JavaScript, then continue. This is because the JS could be doing anything, like appending another element, where the order is necessary. If it queued the script for loading later or made it async, by the time the script finished executing the state of the DOM might not have been the same when the script first started loading.
E.g, consider the following:
<p>Hello</p>
<script>document.body.innerHTML+="Wor"</script>
<p>ld!</p>
In this case, the order of the tags is necessary. If the browser queued the script to be loaded later, the last paragraph tag may have been rendered before the script inserted Wor into the body innerHTML, and you would end up with:
Hello
ld!
Wor`
But what if your script is doing some intense work that could lag out the browser for a few seconds? If you put the script tag in the middle of the body, half the page would be rendered, the script would be run, then the other half would be rendered (after script execution finishes). This gives the impression that the first half loads immediately, but the second half took a few seconds to load.
This causes a bad user experience. Instead, what's recommended is to move the script tag to the bottom, so only once the browser has finished rendering the elements should the script be run. This isn't faster, it just gives the impression of being faster.

"JavaScript placed at the end of the document so the pages load faster" TRUE? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Javascript on the bottom of the page?
I saw a comment in some twitter bootstrap example. It says
JavaScript placed at the end of the document so the pages load faster
Is this true?? If yes then How it works??
There are a number of advantages
There’s no need to have a check if the DOM is loaded, since by having
the scripts at the end, you know for sure it is.
A JavaScript script
file has to be loaded completely before a web browser even begins on
the next JavaScript file. The effect of this, if the JavaScript files
are included at the top of the document, is that it will be a visual
delay before the end user sees the actual page. This is completely
avoided if you include the JavaScript files at the end of the
document.
There are some limitations as well
While including the JavaScript files at the bottom helps us around the
problem of delaying the page rendering, thus giving the impression
that each page in the web site loads faster, it does have a drawback.
If the page is visible to the end user, but the JavaScript files haven’t finished loading yet, no events have been applied to the
elements yet (because everyone uses an unobtrusive approach, right?)
and the user might start clicking around and not getting the expected
results.
If you have proper fallbacks, e.g. a link element which gets content via AJAX if JavaScript is supported and the proper event has been
applied, otherwise it’s a normal link leading to another page, then
the problem isn’t that bad. Still somewhat annoying, though.
Useful Article Here
If the browser encounters a <script> tag, the HTMLRenderer will by default stop and the ECMAscript parser will do its job. The HTMLRenderer will not continue untill all the Javascript code was completely evalutated.
So, if you have many <script> tags and lots of Javascript code in your "upper" HTML code, a viewer of your site might realize a slow'ish loading process.
There are several ways to avoid this issues. The first is, as you mentioned, by just placing all the Javascript code and <script> tags at the very bottom of the <body> element. That ensures that at least all the HTML markup and Stylesheet definitions were fully loaded.
Another options are tag names for the <script> element itself. Such as async and defer will indicate to the Browser / JS Parser that this fill is not required to get loaded and evaluated immediately. For instance
<script async defer src="/foo/bar.js"></script>
The HTML Renderer will realize the tag and store it into a queue, but it will not directly stop and evaluate.
Most browsers execute JavaScript and load the page using the same thread. Hence while JavaScript is executing the page cannot load. Thus if you page contains lots of images or embedded content these assets will not start loading until the JavaScript completes execution.
This is the reason it's advised to put long running synchronous code at the end of the document, or defer it to load when the page loads or the DOM content loads. However modern browsers usually notify the user about long running blocking scripts and allow them to terminate the script if desired.
As important as placing them at the end of the page, is specifying them as async using the HTML5 async attribute. This will ensure that the parser does not stop and parse them but rather continues with the page loading flow and downloads/parses the JS in parallel.
http://davidwalsh.name/html5-async
The logic behind that concept is that since the browser renders your code on the fly, by placing all the html elements before the scripts, it could theoretically load faster than if you had the scripts first, assuming you had an astronomical amount of scripts to deal with.
In practise however no one should ever encounter a situation that would require so much script time that it would affect the load time of a website over more pressing bottlenecks as D/L bandwidth.

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

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