views:

291

answers:

3

Hi guys,

I'll start to develop a new app that uses a lot of heavy js librarys (prototype, scriptaculous, tinymce and so on).

Someone told me to make all the app using ajax, so all the js files will be loaded only once.

My question is, I really must do everything on ajax?

Lets say if I call myapp.com/projects and projects use all those js files, then I click on a "show" link and I'm redirected to myapp.com/projects/1 on this redirect, all js will be reloaded again?

A: 

No, your Javascript files will not be loaded again, they will be cached on the client.

But yes, your application will need to check with the server at every page load, the server often responding that the scripts have not changed. By using AJAX, you reduce the number of connections to the server. You can reduce the number of connections by concating all you Javascript files into one.

Note however that AJAX will add some new problems, like forcing you to track memory leaks as your application will never unload its objects if you never reload a new page.

If you are not at ease with Javascript, I strongly suggest sticking with the "old" model of reloading the page everytime. If you have performance issues, you can deal with them later.

Vincent Robert
A: 

Reloading Images, Scripts, etc...

Short answer: yes


Long answer: depends

When you view a page, your browser will request the HTML, once it has the HTML it will start to load external references (images, scripts, etc...). When it goes to request an image or a script, your browser may send a header which says when it got it last and stored it in its cache. The web server may respond with a 304 Not Modified code which tells the browser to use the cached version saving it from downloading it again.

Even if the browser doesn't use these headers, it will still be caching, it just won't know when the cache should expire. When you use the rails helpers to include images and scripts, it will append a number onto the end of the url which is unique to scripts contents. So if you change the contents, a new url will be used forcing the browser to get the updated version.

Samuel
A: 

Use Google's Ajax Libraries API! Google now hosts the most popular js libraries including Prototype, Scriptaculous and jQuery. Once they host a specific version they are committed to hosting that version indefinitely.

There is a small Rails plugin by Ryan Heath at github:

script/plugin install git://github.com/rpheath/google_ajax_libraries_api.git

Then in your views instead of using the default

<%= javascript_include_tag :defaults =>

use this instead:

<%= google_jquery =>
<%= google_prototype =>
<%= google_scriptaculous =>

You can specify versions if you want. Check out Ryan's readme at github for more information.

This way you don't have to bother setting up an asset host (at least not for your standard javascript) and save yourself a truckload of bandwidth!

ronaldevers