separation of js / css and it's effect on caching

83 Views Asked by At

Say I have the following setup:

Page1.html

  • Includes master.css, page1.css and page1.js

Page2.html

  • Includes master.css, page2.css and page2.js

I have been told that merging the two js and additional css files would be better for caching? But wouldn't the separate files be cached as well? I don't see how this makes a difference (aside from maintainability maybe - personally I like the separation).

what is the most perform-ant and most sensible way to organize something like this?

Disclaimer:: Micro optimization is not the issue here - I would like to know what the best practices are before I begin my project so I do not have to revisit this later.

2

There are 2 best solutions below

3
On BEST ANSWER

The benefit would be:

If the user visits Page1, then Page2, their browser would fetch:

Page1.html
-> master.css
-> page1.css
-> page1.js

Then, some time later:

Page2.html
-> [ no need to re-fetch cached items ]

If the page1.css <-> page2.css and page1.js <-> page2.js are substantially similar, that could (worst-case) save two DNS look-ups, and two HTTP negotiations, which could be fairly slow.

At the very least, you're possibly saving having to "listen to" about 1KiB of incoming HTTP headers twice for page2.css and page2.js. (Although all the major browsers will likely chain those requests together.)

6
On

There are several things to consider here:

  • The size of the page1 and page2 files. If they are very small it's probably not worth the extra overhead of a separate http request to put them in individual files.

  • The total size of your combined files: Some mobile devices are not keen on caching large files.

  • The likelihood of your users hitting both page1 and page2 during their visit to your site.

A side note: If you're worried about the server side organization you can keep the files separated while developing and combine the files into one as a part of your build.