0

So, let say you have 10 pages, which each contains short javascripts such as click on load.

Now, is it more efficient to combine all these javascript into one single file and or leave them on separate pages?

What I am concerning about one single file is that, I don't want extra data being used when you only need one of javascripts. But I heard that I should combine them all into one file.

Steve Kim
  • 5,293
  • 16
  • 54
  • 99
  • http://stackoverflow.com/questions/138884/when-should-i-use-inline-vs-external-javascript – rink.attendant.6 May 17 '15 at 19:06
  • 1
    putting them all in one could save n-1 (9 in your case) http connections. owing to cookies and other per-connect weight, the savings from that far out-wiegh the extra few KB of un-used code. – dandavis May 17 '15 at 19:24

2 Answers2

2

In most cases concatenating your scripts is considered best practice right now since it only requires one request (this will likely change in a few years).

There are a few scenarios where you should make an exception:

  • If your scripts are very large, and if they will only be needed by a few visitors, it may be better to split them into different files.
  • If you need to load and run some JavaScript before rendering the page you will want to keep this code separate. If it is short it is a good idea to write such code inline.
  • You also have to consider caching. If one of your scripts will change very frequently you might want to keep that script in a separate file.

In summary, concatenating your JavaScript is a tradeoff, but in general it is what you will want to do.

Josef Engelfrost
  • 2,955
  • 1
  • 29
  • 38
1

You should put javascript that is shared between several pages into segregated files.

But for just a few onclick actions and very specific small tasks, putting it straight on the page is fine.

The benefit of putting JS in its own file is that the browser can cache it and does not have to reload it every time.

user2936306
  • 236
  • 2
  • 8