简体   繁体   中英

Basic caching js assets in Ruby on Rails

I am at the point where I have a bunch of javascript files and I'm not sure how to approach caching them all in one file. I have come across using:

javascript_include_tag ... :cache => true

but I have a number of javascript files that are particular to a specific page...does it make sense to include all of them in my layout even though some pages do not need a lot of the javascript in there? Some of my pages do not require any javascript at all, is a browser going to download this concatenated js for every page?

Some people will dump all their JavaScript into one file, but I don't think that makes a lot of sense unless the routines are used in every page.

Think about how your scripts are used. Put ones that are used most often in the most pages in one file. Then, if there are scripts used occasionally, put them in separate files. Then use multiple <script> statements in your HTML file to pull in the ones you need.

If a user's browser is set normally, it will download the scripts once then reference them from its local cache. The first time they request the page it'll take a bit longer to retrieve everything because it has to populate the cache, but from then it'll be fast(er). The browser will use the cached version for all references to the script.

The :cache => true flag can help if you have a bajillion scripts, because they could be compressed during the first download of the file but I don't think it speeds up loading afterwards when the browser is pulling them from its cache.

Caching multiple javascripts into one talks about it.

n include tags = n get request on the server. This does not perform well and the web page gets slower.

I would not mind minifying everything into one file. Its a one time download anyways and then it gets cached in the browser.

Each situation is different so analyze yours using Yslow and see if minifying into one file is going to help or not. Also look at https://github.com/thumblemonks/smurf for minifying your js & css in to 2 files.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM