I am building a public facing website and I am using a lot of jQuery and jQueryUI. What I have noticed is that most site on internet that use jQuery and jQueryUI don't have code like this in their pages.
<script type="text/javascript">
$(document).ready(function(){
$("a").click(function(event){
alert("Thanks for visiting!");
});
$( "input:submit" ).button();
});
</script>
I know this is a simplistic example but most sites, for example SO have only one obfuscated js file included for all the pages. It doesn't even seem like they use $(document).ready anywhere. On my current site it seems like I would need to include a js file for each page. My question is how is it suppose to be done and is there a best practice on how to use/include javascript in a page?
You wouldn't see the famous document.ready because most of the code is compressed usually into one big file for caching purposes. Just include your js at the end of the body like:
<script type="text/javascript" src="site.js"></script>
so this can be cached once and for all for every page.
According to W3C you could put scripts almost anywhere: http://www.w3schools.com/js/js_whereto.asp
So where should you put them?
Ege is right to say that you should put them as far down the page as possible because it will enable the browser to load more in parallel up front before it gets to the 'blocking' scripts. See here for more detail: http://developer.yahoo.com/performance/rules.html#js_bottom
Also, it is nearly always a good idea to put your scripts (and CSS) into external files so the browser can cache them tus saving the user from having to download them with the page each time.
Personally, I always use a CDN for script frameworks such as jQuery and the like as they can deliver external resources quicker than you probably can. Also the likelyhood of the browser having already cached jQuery for another site from the same CDN is far more likely. More detail here: http://code.google.com/apis/libraries/devguide.html
Finally, there's nothing wrong with using $(document).ready, but just be aware that this could affect the site's responsiveness and its pros may not outweight its cons. Again, more detail here: http://encosia.com/2010/08/18/dont-let-jquerys-document-ready-slow-you-down/
Hope this helped.
Whether you include the 'site.js' file at the top or bottom doesn't matter, unless your javascript is doing document.write to put something on the page. Then of course at the top would be desired. Some like it at the bottom so that the rest of the page will load before downloading the js file, which can sometimes delay the page load if it is a large file.
Related
I referred the documentation but didn't quite understand it. While working on Javascript with jQuery, I always wrote scripts in the <head>. So why should I write dojo scripts in <body>?
That's not solely Dojo. Loading JavaScript files in your head, means that the entire page is blocked while the <head> is being loaded. Considering the fact that most browsers only support up to 2 simultaneous downloads it means you might be staring at a blank page for a while until the scripts are finished loading.
More can be found at Best Practices for Speeding Up Your Web Site from Yahoo.
The Hello Dojo! tutorial says,
We have also placed the <script> block in the body of the HTML document. We could place it in the header and things would have worked the same, but when you end up in a situation where your application loads a lot of code, having the <script> blocks in the header can keep the page from rendering while they are being loaded. This adds to the user perception of the application "being slow" and can degrade the user experience, so we will generally be demonstrating loading Dojo at the end of the body of the document.
Putting it in the body instead of the head means that the browser can begin to render the page before the script has finished loading: which makes the page-load seem faster.
You also can write your Javascript in a seperate Js-File and just link it in the header
like :
<script type="text/javascript" src="myJavascriptInside.js"></script>
No mixin between Html and Javascript. It's also mentioned in Dimitris link
Best Practices for Speeding Up Your Web Site
Here's a snippet from it:
Using external files in the real world generally produces faster pages because the JavaScript and CSS files are cached by the browser. JavaScript and CSS that are inlined in HTML documents get downloaded every time the HTML document is requested. This reduces the number of HTTP requests that are needed, but increases the size of the HTML document. On the other hand, if the JavaScript and CSS are in external files cached by the browser, the size of the HTML document is reduced without increasing the number of HTTP requests.
This is the way we do it and it works great.
Regards, Miriam
Is there any difference between including external javascript and CSS files and including all javascript and CSS files (even jQuery core!) inside html file, between <style>...</style> and <script>...</script> tags except caching? (I want to do something with that html file locally, so cache doesn't matter)
The difference is that your browser doesn't make those extra requests, and as you have pointed out, cannot cache them separately from the page.
From a functional standpoint, no, there is no difference once the resources have been loaded.
The reason most of the time we see external path for CSS and javascript because they are either kept on a CDN or some sort sort cache server now days on a cloud
Very good example is when you include jquery from google
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
here we see that google is hosting it for us and we don't need to worry about maintainance etc
So if you want to keep them locally then you will have to maintain it
There isn't any difference once the code is loaded. Of course it wont be cached like you pointed out but since you just need to do something locally, it really isn't that important.
On thing to remember would be that you'd have to make sure dependency chains aren't broken since the browser would be loading the scripts simultaneously.
Edit: Of course your main page would appear to take a longer time to load since it has to download all that extra content before the <body> starts to load. You can avert that by moving your JS at the bottom (near the footer) instead.
When your css isnt loaded your page appears crappy at first and then it settles after the css styles are applied, thus now you have to declare your css style on top of the page and then wait for all that to be processed by the browser and then start rendering your page or you let your first page load slowly and on further requests your page will load quicker since the style is now cached
and similarly with your script code, now you need to wait for your code to be rendered on the page and then wait for the the execution that you have bound in $(document).ready().. I hope you realize that $(document).ready will now be delayed since there is no caching.
There is a huge performance issue with this. your load and DOMContentLoaded will fire way slower.
load will fire when browser parses last line of your code. So browser will show waiting circle until all your resources are loaded and parsed. Browsers load multiple resources synchronously. You will lose this performance boost by including JS and CSS code in HTML.
No difference on the client side except you'll do less requests, thus loading faster. On the other hand, you won't be caching but you also won't be able to share the style an the JavaScript among several pages.
If you're positive that CSS and JavaScript are only going to be used in this page, inline is fine IMO.
If you use the script and css only on one page, including them in the html would be the fastest way as the browser needs to make only one request. If you use them on more pages, you should make them external so the browser can cahche them and only has to download them once. Using the jquery from google for example, as mentionned #hatSoft, is even better as the browser is very likly to have them already in cache from othersites that reference them when your user visits for the first time. In real live you rarly use scripts and css on one page only, so making them external is most often the best for performance, and definitly for maintenance. Personaly i always keep HTML, js and css strictly separate!
We can place JavaScript in 3 ways?
as a external file
in <head>
in body <body>
all methods are valid by W3C ?
So How to judge where JavaScript should be placed at bottom or which must be in <head> or in <body>?
I've seen JavaScript on many sites
in <head> ,
as a external js,
just before </body> and
some time anywhere in <body>....<body>
for example: before any other XHTML
tag/code which are going to affect
with that JavaScript code.
update:
I saw mostly people use Google analytics code as a inline javascript at bottom?
In my coding I follow the following rules with regards to JS organisation:
Any JS that is not time sensitive and/or runs after the document is loaded gets put into an external js file and included in the head
Any JS that needs to run as soon as possible is placed in the DOM where appropriate (eg. if you want some code to run as soon as the necessary elements are loaded place the code directly below the last dependent element)
Any external tracking libraries like Nielsen/Google go right at the bottom just before the closing body tag
Related SO posts:
Where should I declare JavaScript files used in my page? In or near </body>?
Does javascript have to be in the head tags?
In most all cases, Javascript should be as an external file, to allow caching and avoid re-downlading the exact same 100+-line script on each page load. (If, on the other hand, it is a script you only expect users to ever see once, then inline is fine.)
Whether or not it goes in head or body is really your choice, though Yahoo recommends the bottom of the body for performance.
If you're concerned with page load times this google article on minimizing your payload size might help. I've linked to the section relating to deferring the loading of javascript. Not exactly what you asked for but might come in handy.
In fact, http://code.google.com/speed/ is just plain handy!
I generally will place as much as I can into external js files. The main exception to this, is information injected into the page server-side at load. I tend to push everything that is not specific to the one page into a library/site js file. If you don't have a need for inline scripts (ie: document.write), then it's best to push your scripts to the bottom before the closing body tag (see YSlow and yahoo's research on why).
If the page/script doesn't NEED document.write, put it at the bottom.
If it does NEED document.write evaluate why.
If it can easily be externalized (into a separate .js) do it.
If it isn't specific to the one page, put it into a .js that is used by multiple pages.
Merge custom site scripts into a single .js where possible.
minify/reduce said .js and use http compression wherever possible.
The primary reasons for this:
Separate your markup from your scripts.
Separate your markup from your scripts.
Separate your markup from your scripts (as much as possible, same as for css)
Create reusable script includes to reduce server requests.
Reduce server requests
Reduce the time to transfer your files.
I'm working on a project which uses many scripts (Google Maps, jQuery, jQuery plugins, jQuery UI...). Some pages have almost 350 kB of Javascript.
We are concerned about performance and I'm asking myself what is the best way to integrate those heavy scripts.
We have 2 solutions:
Include all scripts in the head, even if they are not utilized on the page.
Include some common scripts in the head, and include page specific ones when they are needed.
I would like to have your advice.
Thanks.
For the best performance I would create a single static minified javascript file (using a tool like YUI compressor) and reference it from the head section. For good tips on website performance check out googles website optimizations page.
Note that the performance penalty of retrieving all your javascript files only happen on the first page, as the browser will use the cache version of the file on subsequent pages.
For even better responsiveness you would split your javascript in two files. Load the first with all the javascript you need when the page loads, then after the page loads load the second file in the background.
If your interested, I have an open source AJAX javascript framework that simplifies compresses and concatenates all your html, css and javascript (including 3rd party libraries) into a single javascript file.
If you think it's likely that some users will never need the Google Maps JavaScript for example, just include that in the relevant pages. Otherwise, put them all in the head - they'll be cached soon enough (and those from Google's CDN may be cached already).
Scripts in the <head> tag do (I think) stop the page from rendering further until they’ve finished downloading, so you might want to move them down to the end of the <body> tag.
It won’t actually make anything load faster, but it should make your page content appear more quickly in some situations, so it should feel faster.
I’d also query whether you’ve really got 350 KB of JavaScript coming down the pipe. Surely the libraries are gzipped? jQuery 1.4 is 19 KB when minifed and gzipped.
1) I would recommend gather all the common scripts and most important like jquery and etc in one file to reduce number of requests for this files and compress it and i would recommend google closure u will find it here
2) Make the loading in a page the user have to open it in the beginning like login page and put the scripts at the end of the page to let all the content render first and this recommended by most of the performance tools like yslow and page speed
3) don't write scripts in your page , try to write everything in a file to make it easier later on for compression and encryption
4) put the scripts and all statics files like images and css on other domain to separate the loading on your server
I am learning jQuery and have a created several plug ins.
Unfortunately due to my company's coding practices they want all javascript code to be extract out to js files. This for me poses two challenges:
Can i extract the actual $(document).ready(..) call to a js file? So far with my limited knowledge I have not figured if this at all possible. If not, I welcome any suggestions to make this cleaner and more acceptable way to include this code.
There are too many javascript includes for each asp.net page header since I may be using several plugins. Is there a way to reduce the potential costly server trips that I would need to make each time I need these files?
Any suggestions, corrections are greatly appreciated
thanks
1. Absolutely.
Just add a script reference to your html like this:
<script type='text/javascript' src='js/yourfile.js'></script>
Then just start your .js file with
jQuery(function() {
foo;
...
bar;
});
or any other shortcut ways of starting the jQuery code block.
2. You should run your scripts through something like Minify before sending them off to the user. This will combine the files and pack them in nicely, so that they take up less space.
Using $(document).ready () in an external javascript file is fine - it will work exactly the same :) In fact - not only will it work, but it is good practice as it helps to seperate the content (HTML) from the behaviour (Javascript).
In response to your section question - you can combine all of your plugins into a single javascript file and link to that one inside the <head>. You could also try minifying the scripts, although this is normally a bit overkill until the site goes live.
When I use jQuery, I normally use this kind of structure:
<html>
<head>
<!-- html tags such as title, link, meta etc -->
<script type="text/javascript" src="/path/to/jquery.js"></script>
<script type="text/javascript" src="/path/to/plugin.js"></script>
<!-- more plugins included if required -->
</head>
<body>
<!-- html here -->
<!-- script is the last thing before the ending body tag (increases performance) -->
<script type="text/javascript" src="/path/to/your_jQuery_code.js"></script>
</body>
</html>
I think worrying about server trips for javascript includes is premature optimization. Do you have any evidence that these pages are loading slowly? The browser should be caching the javascript files.
If you do have evidence that this is a problem, you could
-combine the jquery code and any plugins into one file
-write an .net content handler to do this for you (probably overkill)
Then you can add a custom js file per page to handle page specific properties.
You can most definitely put your document.ready and all other JavaScript code in an external file.
Typically I have 2 calls - one for jQuery itself, and one minified global.js file that combines and minifies all of my individual files.
Personally, I like to use front end blender for this, but there are many other options available as well.
there's nothing wrong w/putting the document.ready call in an external file. in fact, it's what i do to separate my js from my html. if you're concerned about certain functions running on certain pages, you may sift through them with a
var path = window.location.pathname;
if (path == "/yourdir/yourpage.html") {
//do something for this page only
}
or you can just include certain files only on certain pages.