Benefits of Loading Js At the Bottom as Opposed to the Top of the Document

Benefits of loading JS at the bottom as opposed to the top of the document

  1. If you include external js files at the bottom of your page, you give the priority of your HTTP requests to the visual display that will be presented to the client instead of to the logic of interaction or dynamics. I believe, if you do not use a content delivery network to deliver images to the client then you are only allowed to process a maximum of 2 HTTP requests at a time. You do not want to waste these requests on logic because we all know how impatient the end user is.

  2. By loading js at then end of the file you can access the DOM(most of the time) without having to call a document.ready() function. You know that if the page render finally makes it to your javascript code that the necessary page elements have usually loaded already.

There are a few more reasons out there but these are the important ones that I try to remember when it feels so awkward to place all js at the bottom.

Benefits of loading JS at the bottom as opposed to the top of the document

  1. If you include external js files at the bottom of your page, you give the priority of your HTTP requests to the visual display that will be presented to the client instead of to the logic of interaction or dynamics. I believe, if you do not use a content delivery network to deliver images to the client then you are only allowed to process a maximum of 2 HTTP requests at a time. You do not want to waste these requests on logic because we all know how impatient the end user is.

  2. By loading js at then end of the file you can access the DOM(most of the time) without having to call a document.ready() function. You know that if the page render finally makes it to your javascript code that the necessary page elements have usually loaded already.

There are a few more reasons out there but these are the important ones that I try to remember when it feels so awkward to place all js at the bottom.

JavaScript placed at the end of the document so the pages load faster TRUE?

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

Is it practically good to put JS files at the bottom of webpage?

Edit: I am adding another point in response to the cotton I'm seeing in peoples ears on this topic.

Additional point #5. If you are seriously concerned about handling behavior on JS-fail and by that I mean, people browsing with JS turned off, what you should be doing is embracing the notion of progressive enhancement. For instance, you could design an accordion menu to act as a flyout-menu on-hover by default, yes with CSS only, and then remove that behavior by changing key classes when JS is enabled. That way users have access to the links without JS if they should turn it off but they get the enhanced behavior when JS is working.

But what you should not be trying to handle is the absence of entire JS files on pages that are supposed to have them because the page was mangled on the back-end. Handling the unexpected is one thing, but handling the failure to finish building an HTML file before it's served should not ever be considered an acceptable scenario in production, especially if you have actual back end code in your templating language (which you shouldn't) waiting to spill out and give would-be hackers something potentially interesting to look at. Broken pages should be served as error messages.

================================

  1. Dead wrong. Any time you use JS to tweak the initial static look of your page, you're doing it wrong. Maintain that separation of concerns and your pages will be much more flexible. Using JS to tweak the STATIC styles of your pages isn't modern, it's bass-ackwards and you can tell the jQuery mobile guys I said as much. If you absolutely must support IE6 and IE7 and IE8 tell your client how much it's going to cost them to cut out rounded gradient corners all over the place if they refuse to accept anything as an alternative to absolute graceful degradation for 5% of their client-base.

  2. If your pages, with no JS beforehand are taking that long to load, you have other problems that need to be addressed. How many resources are you loading? What ungodly pre-processing is your PHP up to? I call back end or design shenanigans.

  3. Are you saying it's half-acceptable to have half a page with working JS rather than completely unacceptable? Don't let go of that client, whoever they are.

  4. jQuery, when minimized is about the size of a medium-sized JPEG.

Note: It is not entirely unacceptable to have some JS up top. Some specialized code like analytics stuff or canvas normalizers require it. But anything that doesn't need to be should be at the bottom. Every time JS is parsed, the entire page load and flow calculation process stalls out. Pushing your JS to the bottom improves perceived page load times and should also serve to provide evidence that somebody on your team needing a swift kick in the butt to figure out why their code is tanking or what could be done with their 25 megabyte png-24s that they just shrunk down rather than reformatted.

What's Pros and Cons: putting javascript in head and putting just before the body close

From Yahoo's Best Practices for Speeding Up Your Web Site:

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.

Therefore, in general, it is preferrable to put them at the bottom. However, it isn't always possible, and it often doesn't make that much of a difference anyway.

Putting js at the end of the page

.ready is a shortcut to DOMContentLoaded (or onreadystatechange or an assortment of workarounds for other browsers). That event fires when the DOM has been built - in other words, when the whole HTML has been downloaded.

So, as long as your script tags are the last thing before </body> (they are not inside any divs or other elements) the end result is the same, you don't need $(document).ready. That is even recommended, since putting your scripts in the <head> will slow down the loading of content.

Though I'd recommend you to adopt this pattern, to avoid problems with the $ global:

<script>
(function($){
$('ul a').click(function(){
alert("")
})
})(jQuery)
</script>

These other questions are interesting reads:

  • How does jQuery's "document ready" function work?
  • Does putting scripts on the bottom of a web page speed up page load?
  • When do you choose to load your javascript at the bottom of the page instead of the top?
  • Benefits of loading JS at the bottom as opposed to the top of the document

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

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.

Why is the standard to put the css and js file at the top and bottom of the page (respectively)?

That's not entirely correct. Said simply:

  • Style declarations should be as close to the top as possible, since browsers won't render your page before loading the CSS (to avoid a flash of unstyled content)

  • Script tags should be as close to the bottom as possible, since they block browsers from parsing after the tag before it is loaded and complete (because the script may change the document with document.write)

If you're interested in frontend performance, I highly recommend reading High Performance Web Sites: Essential Knowledge for Front-End Engineers by Steve Souders.



Related Topics



Leave a reply



Submit