views:

315

answers:

3

In VS 2008, I have an ASP.NET content page having one master page. I would like to add JavaScript functions for client side validation etc. for this page. My questions are:

  1. Should I write these scripts in a separate .js file, or embedded within the .aspx file.
  2. Does this choice affect the performance of the website?
  3. Are there any rules for writing a JavaScript file?
+2  A: 

I would say, you should create javascripts functions into separate .js file and link them up inside the the master page or .ASPX where it's needed.

Imagine you "copy and paste" the javascripts functions in each of the .ASPX, then when that .ASPX file is loaded, it will take longer to render that page since it needs to render also the javascript functions. If you maintain it into separate .js file, the browser will only download once if it's newer or not exist before.

You can also cache those .js files, so that the browsers won't reload it everytime.

The other advantage is when you need to make some changes in the .js files, you just need it to modify it centrally at one file, rather than do a "Find and Replace" through numerous .ASPX

hadi teo
A: 

It depends on your use. If its a page specific functionality then try and implement it in the page itself. If it is used by many pages then put that inside a js file.

Does it affect the performance of website?

Yes, it can. If you have a js file with thousands of lines of code and in a page you have to call only one function inside the js file. If you refer the file for this one there should be a bandwidth wastage in downloading the entire file. For this case you can write the function inside the same page itself.

On the other side browser can cache a js file. So for subsequent requests if the file is present in the cache it won't be downloaded again. But in the case of JavaScript being written in the page itself, every time the page loads all of its contents will be downloaded.

rahul
+2  A: 

You should consider the power of caching, if the JavaScript functions are likely to be used on several pages a user will visit. In this case you should put them in (if possible) one external .js file. With this the file will only get fetched once from the server and then stays in the browser cache. Your HTML pages get smaller (significantly for larger JS libs).

If the functions (typically validation rules) only apply to one single page only, an external JavaScript file would lead to an extra HTTP request that leads to a short blocking in the user's experience of your page. Here it's better to embed the JS in the HTML file.

See Yahoo!'s tips on this for more detailed hints.

Cheers,

Boldewyn