Doesn't External JavaScript files lead to more clientside processing? - javascript

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.

Related

Using separate javascript file for each html page?

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.

Only running javascript required for current page, best methods?

So I know it's best to have one javascript file for an entire site to limit http requests. So obviously only some javascript is required for some pages. What is the best way of only running the javascript required for the current page?
EG.
if(page=='home'){
//run javascript require for the home page
}
Maybe this isn't an issue and if targeting elements are not found on the page javascript will just fail gracefully? I would just like to know the best practice for this javascript structure.
Encapsulate your logic in functions. Then just call the function(s) you need in each page, either via "onload" or an embedded function call in the page:
<script type="text/javascript">
yourFunctionForThisPage();
</script>
Edit: Just to clarify: my answer is assuming the (implied) constraint of a single .js file. As others have pointed out, although you save on HTTP requests, this is not necessarily a good idea: the browser still has to parse all the code in the file for each page, whether used or not. To be honest it's pretty unusual to have a global site-wide js resource with everything in it. It's probably a much better idea to logically split out your js into various files, i.e libraries. These libraries could be page-based - i.e specific code for a particular page, or algorithm/task-based that you can include in whatever pages need them.
Is this feasible?
While it is best to have just a single Javascript file per page to lower the number of requests yet it may not be feasible. Especially the way that you'd like to do it.
If you're asking how to join various scripts of various pages into a single script and then running just those parts that are related to a particular page then this is something you shouldn't do. What good is it for you to have one huge file with lots of scripts (also think of maintainability) compared to a few short integrated scripts? If you keep the number of scripts low (ie. below 10) you shouldn't be to worried.
The big downside is also that browser will load the complete script file which means it will take it more time to parse them as well as consume a lot more resources to use it. I'd strongly suggest against this technique of yours even though it may look interesting...
Other possibilities
The thing is that the number of Javascript files per page is low. Depending on the server side technology you're using there are tools that can combine multiple script files into one so every page will just request a single script file which will combine all those scripts that this particular page will use. There is a bit overhead on the server to accomplish this task, but there will be just one script request.
What do you gain?
every page only has scripts that it needs
individual script files are smaller hence easier to maintain
script size per request is small
browser parsing and resource consumption is kept low
Know what you will need on the page and use a script loader like labjs.
Also, remember that your specific case might be different from what others have found, so you might want to do some tests, to verify if, for example, having 5 little files, is better (or worse) than 1 big file.
The only way to be sure is to test different options yourself and come up with a fitting solution.

Speed optimizing a JavaScript function

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.

Which is better for JavaScript load-time: Compress all in one big file or load all asynchronously?

A simple question that I'm not sure if it has a short answer!
Description
I have a files of JavaScript that to be loaded in a website here are some notes about them:
They are all comes from the same domain (no cross domain loading needed)
They are identical around the website.
There are several files, like jQuery, and 5 other plugins plus my own application script that is based on them.
Their size all compressed = 224KB, ( I combine all the files in one file then I compress them at once using YUI Compressor 2
Problem
I've heard that 224KB is not ideal to be in one file! and it should be split into several files with maximum of 44KB each .. I can't recall when I've heard this and I'm not sure if it's effective to split it into more files, but It's true that 224KB takes long time to load for the first time, consider that the website is loaded with images and css of course.
I've minimized the need for the early loading of JavaScript file and put it on the bottom, so far this is a good progress but I need to load it assynchounosly with the HTML to gain time Source and the decission to make is:
Yes or No?
Keep it in one compressed big file? or to split them into many compressed file and loaded a asynchronously (I'm aware of handling the dependency related problems)?
It depends on what the site is and how important first load time is for it.
Regardless of that though, I'd probably load JQuery and stuff like that from a public CDN. One big benefit is that it might already be cached even if they have never been to your site.
http://encosia.com/2008/12/10/3-reasons-why-you-should-let-google-host-jquery-for-you/
The Cappuccino team is a big proponent of one file -- they make a javascript framework. Apps made with their tool are expected to have some load time.
http://cappuccino.org/discuss/2009/11/11/just-one-file-with-cappuccino-0-8/
Another benefit of loading JQuery and related from a public CDN would the increased requests by destination. I believe the client is restricted to 2 requests per domain, so by loading jquery from google, and a plugin from jquery, and your custom app code from your own domain, the browser can execute these concurrently rather than waiting for the first two and then issuing a third request.
I guess this adds another performance improvement over one large file as well. Even if you just split that 1 file into 2, it could be retrieved with 2 concurrent requests from the browser potentially improving load time.
Here's what we did to make our web app fast.
The main JS and CSS files are compressed and put inline with the HTML markup.
The white spaces of the HTML are removed and the images are converted to data:image/png by a shell script.
The size is ~400kb but cached and gzipped.
The mobile version of the web app is the same but at ~250kb.
It means the whole app is ready to run, like an executable, in a single http call.
Then a second http call get the data(JSON), and we use PURE to render it in HTML using the existing markups in the page as templates.
The app is divided in modules, only the common modules are preloaded this way.The others are coming when requested by the user.
There is no exact answer to this question. It pretty much depends on how and when you are making use of those files.
Typically, you only want to download JS files on pageload which are universally required by the web app. Module specific or page specific JS files shouldn't be compressed in the main JS download and would ideally be loaded on demand.
Also, this question is valid only if you are concerned about user experience for first time users. The JS files would be cached anyways for every other visit.

Should Javascript be separated into files by page or consolidated into one file?

Should I be separating my js for each page assuming there is no overlap and putting references on each page instead of having one master file? what is typical practice? thanks
Everything that is common to every page of your site should be on a single file, since it will be loaded only once by the browser.
Code specific for a single (or maybe 2) page(s) should go on separate files, loaded only by the pages that need them.
That's the way I do it: you use the browser's cache to reduce your bandwidth and to accelerate the loading and rendering of the page.
For infrequently accessed pages, load the javascript inline (at bottom of all the markup) for quickest load time (one less TCP connection required as is the case for separate .js script file).
For frequently hit pages do the opposite: reference a .js script file - in this case the caching by the browser provides a greater advantage across the aggregate of page loads.
In larger projects, develop your javascript in separate .js files (you can use the module pattern for instance), then for production compile them into a single file (or a number of files per architecture of your application) with a build script.
It all depends on what kind of app you have. If your app is frequently accessed but for short periods of time then initial loading time is important and you should try to combine files.
If, however, you expect users to spend hours at a time in your app and initial load time is not critical then I would advise partitioning your .js files as much as you need to to make it readable - since they will all be cached anyway after the initial load.
Don't believe the hype. Unless you're a google search engine you should be careful not to sacrifice readability for the sake of a few seconds (or less) at initial start up. Put it another way, rules of thumb are just that, don't neurotically follow them - think first :-)

Categories

Resources