I have a number of JavaScript functions like the following on my page:
function fun1(){...}
function fun2(){...}
function fun3(){...}
function fun4(){...}
I may use fun1 in one or two pages, but the other functions only for specific pages.
My question is: should I include all the functions in one file like script.js or include specific functions for specific page? Which one is better for speed optimizing?
I guess your question is about optimizing page loading speed.
I would suggest grouping them as mush as possible in a single js file.
Otherwise, you would have to load a lot of small js files, increasing the page loading time.
Consider minifying your JS files too.
Depends on the size of the functions, your visitors' access patterns, your cache settings and other circumstances. The speed of downloading a file depends on how many TCP packets the server has to send. (Packet sizes tend to be around 1,5K.) Increasing the file size only matters if means the file needs to be broken into more packets (the client-size delay of processing a script which needs not be run is negligible), so if your scripts are short (you should of course minify them first), its best to alwaays bundle them. If you expect the average visitor to need all scripts eventually, it's again best to send them in one file. If, however, the average visitor won't need some of the larger scripts (for example one part is only needed at upload, and only 0,1% of the visitors ever uploads something), it might be better to send them separately.
The .js files are cached by your browser. So you can include as many functions as you like in a single file. If you split them into separate files that much of additional calls are made from the browser which slows down the loading page.. Also you can compress the js files if you are concerned about the size of the .js file ..# http://javascriptcompressor.com/
It depends a lot on how your server is sending out these files. If you have Firebug, open up the Net tab and inspect your JS files. If you see a Last-Modified entry in the Headers tab, it means that you are better off putting all your JS into one file. If you don't see it, it's best to split things up into page-specific files.
In my opinion, there are four main methods of speeding up your page-load times:
server headers -- this one is more complex to set up, but if you control your server settings or if you are willing to serve your JS via a dynamic page (PHP or ASP), you can send extra instructions to the browser to cache specific content for specific periods. Since your JS files are likely to change quite infrequently, it's usually pretty safe to do this for them. You basically just need to set the Expires header to some point well into the future. This means that the browser will not need to request the file at all if it has it in the cache. This makes the most sense if you have visitors who come back again and again. If you get a lot of one-hit visitors, this won't make a difference. This does mean that if you change these files, many browsers won't pick up the change; thus you should either change the file name or append something to the query string like this: <script type="text/javascript" src="/sitescript.js?v=1.1"></script>. This can be a maintenance problem if you have more than a few static HTML pages.
numbers of files -- in my opinion, this is where you get the biggest bang-for-buck savings. I'm nearly certain that most browsers still support only four active requests at a time. That means that if your web page has five images, the last image won't get requested until one of the previous images completes loading. And if your site has 50 images and 3 CSS files and 10 JS files, it's going to take a while to clear all those requests. Remember, even if you are sending Last-Modified headers, the browser still needs to check if the content has changed, so it needs one of those request slots. If you can combine all your images into a single images (using CSS sprites) and all your JS into a single file, your pages will load significantly faster.
file size -- as the web speeds up, this gets less and less important. If your server does not support content compression, it's a pretty good idea to minify your JS, though the time savings are overrated in my opinion. This does make maintenance somewhat more time-consuming and live debugging nearly impossible, but it definitely brings file size down quite a bit. If you have a LOT of JavaScript (maybe ~150KB+?) or if you know your visitors are coming from slower networks (for example, people on a corporate network), I would recommend doing it. If your server DOES support compression, the savings are actually negligible.
script placement -- when the browser hits a <script src="..."> tag, it halts all rendering until the script has loaded and executed, which means an inevitable delay. If you put your scripts in the middle of your page, you'll note that half the page loads and then pauses. To speek up rendering, place as many of your <script> references as you can at the dead bottom of the page. Scripts that you need at the top of the page can go there, but the more <script> clutter you have up there, the slower the page will render. Any code that gets executed by onLoad or DOMReady can safely go at the bottom of the page.
Yahoo has a really quite amazing list of optimization tips at their Best Practices page.
Related
Which would result in greater speed/efficiency: Referencing one JavaScript file for all files in the directory OR referencing a different JavaScript file for each file in the directory?
So basically, referencing the same JavaScript file in all web pages vs a unique JavaScript file for every webpage.
Note: I thought that referencing the single file would be slower as there is code in there that is obsolete to some files, thus running useless code and causing the file to run less efficient.
There are tradeoffs involved so you may ultimately need to measure your specific circumstances to be sure. But, I'll explain some of the tradeoffs.
If you have giant amounts of data or giant amounts of code that are only used in one or a few pages, then you will probably want to separate that out into its own file just so you can ONLY load it, initialize it and have it take memory when it's actually needed. But, note with the amount of memory in modern computers (even phones these days), the data or code has to be pretty large to warrant a separate download.
Other than item 1, you pretty much always want to optimize for maximum caching efficiency. Retrieving a file (even a larger file than needed) from the cache is so massively much faster than retrieving any file (even a small file) over the network that you really want to optimize for caching. And, the time to retrieve these files generally dwarfs any of the JS parse time (CPUs are pretty fast these days) so triggering an extra download to save some JS parse time is unlikely to be faster.
The best way to optimize for caching is to have most of your pages reference the same common script files. Then, they get loaded once when the viewer first hits your site and all subsequent loads come right from the browser cache. This is ideal. This caching efficiency easily overcomes having some unused or untriggered code in the master file that is not used in some pages.
Lots of small downloads (even from the cache) is less efficient than one larger download. More separate requests generally just isn't as efficient for either the browser or the server. So, combining JS files into larger concatenated files is generally a good thing.
There are limits to all of this. If you had completely separate code for 100 separate pages all concatenated together and each piece of code would search the DOM for multiple page elements (and not find them 99% of the time), then that's probably not an efficient way to do things either. But, usually you can make your shared code smarter than that by breaking things into categories based on a high level class name. So, for example, based on the presence of a class name on the <body> tag, you would then run only part of the initialization code, skipping the rest because its classification is not present. So, when combining code, much of which won't be relevant on any given page, it's wise to be smart in how you decide what initialization code in the shared file to actually run.
You need to measure for your specific case - as every site/page have its own balance between loading less files/loading extra unnecessary scripts (same apply to CSS too).
Generally single file is faster in HTTP v1 as there are restrictions on total number of parallel downloads, HTTP v2 should be removing the difference.
Although it is always recommended to put JavaScript and CSS code into appropriate files (as .js and .css), most of major websites (like Amazon, facebook, etc.) put a significant part of their JavaScript and CSS code directly within the main HTML page.
Where is the best choice?
Place your .js in multiple files, then package, minify and gzip that into one file.
Keep your HTML into multiple seperate files.
Place your .css in multiple files, then package, minify and gzip that into one file.
Then you simply send one css file and one js file to the client to be cached.
You do not inline them with your HTML.
If you inline them then any change to the css or html or js forces to user to download all three again.
The main reason major websites have js & cs in their files, is because major websites code rot. Major companies don't uphold standards and best practices, they just hack it until it works then say "why waste money on our website, it works doesn't it?".
Don't look at examples of live websites, because 99% of all examples on the internet show bad practices.
Also for the love of god, Separation of concerns please. You should never ever use inline javascript or inline css in html pages.
http://developer.yahoo.com/performance/rules.html#external
Yahoo (even though they have many inline styles and scripts), recommends making them external. I believe google page speed used to (or still does?) do the same as well.
It's really a logical thing to have them separate. There are so many benefits to keeping CSS and JS separate to the HTML. Things like logical code management, caching of those pages, lower page size (would you rather a ~200ms request for a 400kb cached resource, or a 4000ms delay from having to download that data on every page?), SEO options (less crap for google to look through when scripts/styles are external), easier to minify external scripts (online tools etc), can load them synchronously from different servers....
That should be your primary objective in any website. All styles that make up your whole website should be in the one file (or files for each page, then merged and minified when updated), the same for javascript.
In the real world (not doing a project for yourself, doing one for a client or stakeholder that wants results), the only time where it doesn't make sense to load in another javascript resource or another stylesheet (and thus use inline styles/javascript) is if there's some kind of dynamic information that is on a kind of per-user, per-session or per-time-period that can't be accomplished as simply any other way. Example: when my website has a promotion, we dump a script tag with a small JSON object of information. Because we don't minify and merge multiple files, it makes more sense to just include it in the page. Sure there are other ways to do this, but it costs $20 to do that, whereas it could cost > $100 to do it another way.
Perhaps Amazon/Facebook/Google etc use so much inline code is so their servers aren't taxed so much. I'm not too sure on the benchmarking between requesting a 1MB file in one hit or requesting 10 100KB files (presuming 1MB/10 = 100KB for examples' sake), but what would be faster? Potentially the 1MB file, BUT smaller requests can be loaded synchronously, meaning each one of those 10 requests could come from a separate server/domain potentially, thus reducing overall load time.
Further, google homepages for example seem to dump a JSON array of information for the widgets, presumably because it compiles all that information from various sources, minifies it, caches it, then puts in on the page, then the javascript functions build the layout (client side processing power rather than server-side).
An interesting investigation might be whether they include various .css files regardless of the style blocks you're also seeing. Perhaps it's overhead or perhaps it's convenience.
I've found that while working with different styles of interface developer (and content deployers) that convenience/authority often wins in the face of deadlines and "getting the job done". In a project of a large scale there could be factors involved like "No, you ain't touching our stylesheets", or perhaps if there isn't a stylesheet using an http request already then convenience has won a battle against good practice.
If your css and javascript code is for a global usage, then it is best to put them into appropriate files.
Otherwise, if the code is used just by a certain page, like the home page, put them directly into html is acceptable, and is good for maintenance.
Our team keeps it all seperate. All resources like this goes into a folder called _Content.
CSS goes into _Content/css/xxx.js
JS goes into _Content/js/lib/xxx.js (For all the library packages)
Custom page events and functions get called from the page, but are put into a main JS file in _Content/js/Main.js
Images will go into the same place under _Content/images/xxx.x
This is just how we lay it out as it keeps the HTML markup as it should be, for markup.
I think putting css and js into the main html makes the page loads fast.
Usually, the javascripts of the main page is heavier than other pages. For example, we put jQuery slideshow in the main page which is not used in other pages. Is it necessary to create different s for the main and individual pages to include only in-action javacript files?
Or all javascript files read on the first page will be cached for browsing the website, and in loading an indivitual page, browser will not read the javascript of slideshow?
Another form of this question is: if I put slideshow on each individual page, will the browser load the slideshow javascript file each time, or it will read from its cache (saved on the visitor's computer)?
like florian h says most browsers will cache the content (unless development tools are being used).
if you only use the slideshow javascript on one page I would recommend putting it in a separate file. There is a downside to this, most often the http requests take the longest time with loading a file.
So if you for example have one javascript file of 1mb and you need all the javascript on most pages its better then using 4 smaller files of 250kb each. Because your browser needs to do 4 separate requests.
Ofcourse this maybe is a difference of a couple of milliseconds of performance profit, so you might want to choose to do it in separate files anyway to increase maintainability.
Allmost all browsers will cache the javascript files, so you shouldn't create different versions for sub pages.
But if you have very large JS files it's of course reasonable to only include those that you actually need.
All files are cached in the browser based on the path to the file.
If you include an javascript from one page, the file will be cached and it won't be downloaded again when you surf other pages.
Unless you want it to ;)
Yes, js files will be cached (if not said otherwise).
But, js files must be processed and may include initialization logic that you do not need. Also every script tag that loads external js will block any other "http thread", meaning images, css files... will stop loading untill js file is loaded, otherwise you will have several parallel (at same time) resources loading.
I would have different scripts for different pages.
For your case it might be an issue and it might not be. You should make few test for you case and see whether do you have performance issues. If not than convenience of not having different scripts for different pages might be better.
I use External JavaScripts in a website as I always try to keep JavaScript at bottom and external.
But Google page speed is giving this suggestion
The following external resources have small response bodies. Inlining
the response in HTML can reduce blocking of page rendering.
http://websiteurl/ should inline the following small resources:
http://websiteurl/script.js
This external js file has only this content
$(document).ready(function() {
$("#various2").fancybox({
'width': 485,
'height': 691,
});
});
But in Yslow I get this suggestion
Grade n/a on Make JavaScript and CSS external
Only consider this if your property is a common user home page.
There are a total of 3 inline scripts
JavaScript and CSS that are inlined in HTML documents get downloaded
each time the HTML document is requested. This reduces the number of
HTTP requests but increases the HTML document size. On the other hand,
if the JavaScript and CSS are in external files cached by the browser,
the HTML document size is reduced without increasing the number of
HTTP requests.
Which is right Google or Yahoo?
This is a bit of a problematic example, on quite a few fronts.
You can organise your scripts in such a way that you do not need to inline that JS. For example you could have a common.js file that runs that snippet, other similar snippets and simplifies your code.
Additionally, this seems to have awoken "never inline any JavaScript EVER" architecture police. Turns out that sometimes it is a best practice to inline JavaScript, for example look at the common snippet from Google analytics.
Why are Google suggesting you should inline this tiny script?
Because 20% of the page visits you get have an unprimed cache
If you have a cache miss, it is likely a new connection to your site will need to be opened (1 round trip) and then the data delivered in the 2nd round trip. (if you are lucky you get to use a keepalive connection and it is cut to 1 round trip.
For a general "global" English web application you are looking at a typical 110ms round trip time for a service hosted in the US. If you are using a CDN the number would probably be halved.
Even if the resource is local, the web browser may still need to access the disk to grab that tiny file.
Non async or defer JavaScript script tags are blocking, if this script is somewhere in the middle of your page, it will be stuck there until the script downloads.
From a performance perspective if the only 2 options are:
Place a 50 char JavaScript bit inline
Place the 50 chars in a separate file and serve it.
Considering that you are a good web citizen and compress all your content, the amount of additional payload this adds is negligible compared to the 20 percent risk of giving people a considerable delay. I would always choose #1.
In an imperfect world it is very rare to have such a clear and easy set of options. There is an option 3 that involved async loading jQuery and grabbing this functionality from a common area.
Making scripts inline can have some detrimental effects -
a) Code organization - Your code gets scattered in between your markup, thus affecting readability
b) Code Minification and obfuscation becomes difficult
Its best to keep your js in seperate files, and then at build time integrate all of them into a single file, and minify and obfuscate this.
This is not quite true. You can configure the web server (well atleast apache) to make the scrips/ccs inlined when they are served.
Here is a useful link
http://www.websiteoptimization.com/speed/tweak/mod_pagespeed/
There are two factors to consider here. One is download time, the other is maintainability. Both of these are impacted by how many times a piece of Javascript is needed.
With respect to download time, you obviously have two choices: include the JS in the body of the page, or as an external file. Including the JS in the body does save an extra HTTP request, although it also bloats the HTML a bit and can be a pain to maintain if you have several scripts you're putting inline on several different pages.
Another important consideration is whether or not the JS is needed immediately on the page. If a small piece of JS is needed as soon as the page loads, then putting it inline may be a good idea. If it's being used for something asynchronous in the future, then putting it an external file may still be a good choice.
I usually write javascript inline, especially if the script is this small. I would say just paste it in your code. It won't increase the http document size by a lot.
While inlining the script will save a request, as Yslow suggests it increases the HTML document size, and mixes content/markup with code/logic, which you generally want to avoid from as much as possible.
The reason Yslow gives this caveat:
Only consider this if your property is a common user home page.
Is that if the page is loaded frequently, it's worth it to have the javascript external, since the files will be cached in the browser. So, if you combine your JS into one file, on the first request you incur one extra request, and on subsequent requests the file is loaded from the cache.
Aaron Peters talk from last year's Velocity EU gives a good insight into the options, and course you should choose - http://www.slideshare.net/startrender/fast-loading-javascript
For really small snippet of js it's really not worth putting them in an external file as the network overhead of retrieving them will dwarf the benefits.
Depending on the latency it may be ever worth including large scripts e.g. Bind mobile has loads of js in the first page loaded which it then cached in localstorage for later pages.
Addy Osmani recently put together a experimental library to help people play with caching scripts in localstorage - http://addyosmani.github.com/basket.js/
I was thinking about external HTML files, and it occured to me, that if I group the functions from several HTML pages, in one JavaScript this will lead to extra clientside processing.
Basically, I would like some idea of whether this is correct.
Here is my thinking. Suppose I have one JavaScript file for five pages. If the user goes to each page, for each page he has to load not only the JavaScript for that page, but the JavaScript for the other four pages. The final sum is the user's browser loaded about 5 times as much JavaScript as he would have normally.
I think most people group there JavaScript by common functionality. So you can have the JavaScript file with several pages, however you may not use all the JavaScript on every page. So all the JavaScript you don't use on every page is run/loaded without need.
I have a sub-question. I know you don't have to redoanload the JavaScript file for each page. Is the JavaScript file run each time? Is the JavaScript reloaded? By reloaded, I mean what kind of over head is there for each time the browse has to get a file out of the cache?
Thanks,
Grae
If I have a file of 200 lines, and seperate it out to 5 files of 40 lines each, the total number of lines remains at 200 BUT. remember that, if I pulled files 1-4 on the previous page, I only now need to pull file 5 since 1-4 are in my cache. additionally, most modern browsers are goint to thread those requests so instead of a single large file download for a single file, I get 5 threaded downloads of smaller files.
the overhead for the browsers would be pretty browser specific in how they handle it and above my head on exact implementation.
the user goes to each page, for each page he has to load not only the JavaScript for that page, but the JavaScript for the other four pages
If caching is set up correctly, the contrary will be true: The file will be loaded only once, at the beginning of the user's visiting the site. The overall amount of data to load will be reduced in most cases.
The JavaScript code for all four pages will be loaded in the browser's memory somehow, maybe even pre-parsed (I don't know the exact specifics of this), but that part of script processing is totally negligible.
It could still be wise to split your JS library into chunks, if they are totally separate on every four pages and really huge - it will depend on your script's structure. But mostly, having one external file, and therefore one slightly bigger request the first time but none afterwards, is the preferable way.
For your sub-question, take a look at Firebug's "Net" tab. It will show you which resources it loads and from where, and how long it takes to process them.
It's better to pack the javascript for all pages into one file. The file will be cached and not downloaded again by the browser for consecutive requests. The reason is that making a web request is far more expensive for your server and the client than for the client to parse the javascript-file.
Browsers are so fast these days that you don't have to worry about the client having to load some extra javascript that might not be used for that specific page.
To make your site fast, you should focus on keeping the amount of requests to an absolute minimum.