Whether we need a separate external JS file for each of our web pages?
I am part of the performance team, and we are responsible for making performance guidelines for our development team. Here is an article which I wrote earlier where I am talking about why you should not have separate JS file for each of the page that you create.
This article talks in great details about the performance implications of having page specific JS files, why they should be avoided and what can be the alternate solution.
Though, I have written this article, I have brought the recommendations or suggestions from other blogs. Wherever any outside blog is referred I have given an external link. You should read these external articles to get complete hold of the context.
Here it goes:
I have spent quite a few hours with our team in discussing whether you should have a page specific external JS file.
I tried my best to answer most of the questions raised by you guys; however there were great concerns that we are defying our basic best practice of not writing JS code directly into the page.
Why developers are reluctant to accept this to be a best practice followed in industry? I will answer this from directly from one of the book I referred during the preparation of best practices document:
“For developers who have been trained to write modular code (whether in JavaScript or some other programming language), this suggestion of combining everything into a single file or writing it inline seems like a step backward, and indeed it would be bad in your development environment to combine all your JavaScript into a single file. One page might need script1, script2, and script3, while another page needs script1, script3, script4, and script5.”
I have spent a considerable amount of time over the last 2 days in collecting all the statistics and information to make it clear that why we should not be creating a JS file for each of our pages.
This mail is going to be quite a lengthy mail, so those of you who are not interested in reading through rest of the material, here is the conclusion:
“You shouldn’t have a page specific JS file.”
Main reason behind this recommendation: Only 10–20% of the end user response time is spent downloading the HTML document. The other 80–90% is spent downloading all the components in the page.
Let’s begin:
I will start by jotting down all the concerns raised by the team one by one and then will try to explain that why that is actually either evading the best practice or is clearly not a best practice:
- Having external JS file makes your code more readable.
- There is always a tradeoff when you want to follow a best practice.
- I like keeping my files outside the page as it is cleaner.
- Having external JS file is a best practice as written in coding standard document.
- Having external JS file doesn’t hurt server, as server has considerably high configuration and can create and respond to multiple requests at the same time.
- If you don’t want to create external files, why create one for master page also. Keep your code directly into the page as it will be delivered with the request always.
- External JS files helps in caching.
- In case when the page is not getting saved quickly (this is mostly the case with heavy pages e.g. in Cascade, Heatmap and VendorExtranet) we prefer keeping JS in a separate file. This saves a lot of development efforts because we will need to just open the JS and make all the changes.
References:
In this article I will be using references from following 2 sites/blogs and 1 book.
- Yahoo’s performance research team’s article in 6 series.
o Part 1
o Part 2
o Part 3
o Part 4
o Part 5
o Part 6
This is a very interesting series, despite being lengthy. I would rather like you to go through all the 6 links however, not all 6 articles are relevant to the argument in consideration here. For this argument’s sake please refer only articles 1, 2, 4 and 6.
- Google developer blog’s article about round trip time, its impact on web page and how to reduce it. All the recommendation here are mentioned in our coding standards document in one way or the other. For this particular argument I would like you to refer section titled: “Combine external JavaScript”
- A book titled: “High performance web sites – Steve Sounders”. He is from YUI performance team at yahoo. This book gives 14 best practices and it is recommended to go through them all however for this point you will need to go through chapter 1 and chapter 8.
Time to dissect:
Before I start I will answer the most important question and that too in just one word:
Q. Why do we follow best practices?
A: To reduce PLT.
1. Having external JS file makes your code more readable.
How readable is the following code?
var _0xe4f9=["\x48\x65\x6C\x6C\x6F\x20\x57\x6F\x72\x6C\x64\x21","\x0A","\x4F\x4B"];var a=_0xe4f9[0];function alert(_0xda6cx3){alert(_0xda6cx3+_0xe4f9[1]+a);} ;alert(_0xe4f9[2]);
It’s not readable. This is an obfuscated version of a code. Obfuscation is a process followed religiously by all the companies. E.g. All the SP js are obfuscated, JQuery js is obfuscated etc.
Why? When you consider the performance metric, readability does not make an entry. I as a developer will not going to make a code readable at the cost of my PLT.
We do not write code to make it readable.
We write code to achieve certain functionality in a best possible way. While trying to achieve something in a best possible way our code ultimately becomes readable. The problem here is, you start writing your code with this thought in mind that I want to make it readable.
What you need to understand is readability is not the aim, it’s a byproduct.
One argument that comes close to counter this is why then we follow naming conventions? Yes, we follow naming conventions to make our code readable. However, naming conventions are not just to make your code readable but scalable. A developer when opens his own code 10 days after he had last written it will not be able to make sense of its head and foot unless the code is written with proper variable names and commenting.
So think about it this way: writing code with proper naming convention isn’t really a step towards writing your code in the best possible way?
2. There is always a tradeoff when you want to follow a best practice.
There might be in certain cases, but that is not the case with this particular recommendation.
3. I like keeping my files outside the page as it is cleaner.
Read point 1 with replacing word readable with cleaner.
4. Having external JS file is a best practice as endorsed by other companies.
Coding standards doesn’t outlines that you need to have a separate JS file for each page you are writing. On the contrary if you actually open the coding standards document you will notice a note that goes like this:
Note: Though it is mentioned to split scripts into 2, care should be taken to monitor the number of files that are being requested. Combined files are a way to reduce the number of HTTP requests by combining all scripts into a single script (at most 2), and similarly combining all CSS into a single style sheet. Combining files is more challenging when the scripts and style sheets vary from page to page, but making this part of your release process improves response times.
5. Having external JS file doesn’t hurt server, as server has considerably high configuration and can create and respond to multiple requests at the same time.
Server might, but can client handle it?
Its not about the performance of the server but client. By default you client browser’s limit the number of parallel downloads per hostname (in IE its 2). So at most only 2 files will get downloaded at a time. Consider this situation, SP requires multiple JS files for its own functioning. On top of that you are adding multiple requests for your own JS. Does that by any way help in getting the page load faster? On the contrary it in-fact deteriorates page’s performance.
Consider following example, taken from Google developer’s blog:
Here we are downloading 13 different files, and it takes browser 4.46 seconds to download these files.
Consider an alternative design, where you combine all of these files into one:
And suddenly your page request time dropped to 1.87 seconds.
We are downloading the same amount of data, then how the sudden drop from 4.46 to 1.87 seconds? This is because of reduced number of http requests which results reduced RTTs.
6. If you don’t want to create external files, why create one for master page also. Keep your code directly into the page as it will be delivered with the request always.
7. External JS files helps in caching.
On the outset these 2 points might look completely unrelated, however they are not. I will try to explain these 2 points together.
Consider the following scenario taken from “High Performance web sites” book.
This is the case when a user visits http://www.yahoo.com for the first time, with empty cache. Now consider second visit:
Isn’t caching cool?
Now to take advantages of caching, we need to have external JS files. That clearly answers the first question that why you should place your common code into external JS files and not directly onto the page itself.
Now second point: If caching is so cool why not use it for each page?
Table 1. Empty and Full Cache Summary to load http://www.yahoo.com
Now the question: How many users actually view a high traffic site like yahoo with full cache?
The answer of this question is given clearly in part 2 of YUI blog mentioned above. Here, I will mention in brief about the experiment they carried and its answer.
Experiment: From YUI blog: – The performance team at Yahoo! ran an experiment to determine the percentage of users and page views with an empty cache on some of Yahoo!’s most popular pages. We defined the experiment to measure users’ cache behavior related to a new component (an image). For this new image we measured the following statistics each day:
- What percentage of users requested the new image?
- What percentage of page views requested the new image?
Result: Figure 3 shows the percentage of users and page views with an empty cache plotted over each day of the experiment. On the first day of the experiment, no one had these images cached so the empty cache percentage was 100%. As the days passed more users had the images cached, so the percentages dropped until at some point it reached a constant steady state.
Figure: Percentage of Users and Page Views with an Empty Cache
40-60% of Yahoo!’s users have an empty cache experience and ~20% of all page views are done with an empty cache. To my knowledge, there’s no other research that shows this kind of information. It says that even if your assets are optimized for maximum caching, there are a significant number of users that will always have an empty cache. This goes back to the earlier point that reducing the number of HTTP requests has the biggest impact on reducing response time. The percentage of users with an empty cache for different web pages may vary, especially for pages with a high number of active (daily) users. However, we found in our study that regardless of usage patterns, the percentage of page views with an empty cache is always ~20%.
20% empty cache for the page that is among the most active pages on internet. Think how active your page is in MS Corp net? Another point to consider is that cache size is always limited. So with time browser will start removing contents from cache to accommodate newer contents. And if your page is not among the pages which are visited frequently by users it is very much possible that each time user will request that page he will do that so with an empty cache.
8. In case when the page is not getting saved quickly (this is mostly the case with heavy pages e.g. in Cascade, Heatmap and VendorExtranet) we prefer keeping JS in a separate file. This saves a lot of development efforts because we will need to just open the JS and make all the changes.
Being a developer myself I know how irritating it is when SPD refuses to save the code you have written with so much of hard work. However, please refer to the first line of this section and you will that our aim while writing the code is always reduce PLT and nothing else. Here by keeping files externally you have made the job easier for yourself but PLT will suffer for the rest of page’s life. I do understand how difficult it is to follow this, but I will urge all of you to do it like this:
- During your development cycle keep your JS code externally.
- Once the page is finalized, open the page in browser and place the external JS content in a CEWP.
This will make sure you adhere to the best practices require to reduce PLT.
9. What would be an ideal alternative?
I would reiterate my point here “It is not recommended to have a page specific JS file and should be avoided in most cases”, however, if it unavoidable in certain case I would recommend having a dynamic script tag added to your page post load. Code for this approach can be found in the attached e-book, for your convenience I am attaching the code sample here:
|
<script type=”text/javascript”> function doOnload() { setTimeout(“downloadComponents( )”, 1000); } window.onload = doOnload; // Download external components dynamically using JavaScript. function downloadComponents() { downloadJS(“test.js”); downloadCSS(“test.css”); } // Download a script dynamically. function downloadJS(url) { var elem = document.createElement(“script”); elem.src = url; document.body.appendChild(elem); } // Download a stylesheet dynamically. function downloadCSS(url) { var elem = document.createElement(“link”); elem.rel = “stylesheet”; elem.type = “text/css”; elem.href = url; document.body.appendChild(elem); } </script> |
Hope this article have answered all of your queries. Please, leave a comment if you need further clarification. However I would encourage you to comment only after you have also read attached links as I believe they must be able to answer all your queries.





