Reputation: 1476
Assume a website running on a Linux server. There are three pages. One page has an AJAX call, one has a JavaScript-generated calendar, and the third has a lightbox image gallery. They also share some common JavaScript functions.
There are two ways I've handled this kind of setup before. Method 1: create four .js files. One with the common functions (loaded on every page), and three more with each distinct page function. Each page loads two scripts: the common script, and the specific script for that page's content. The page makes one extra HTTP request, but doesn't load any extraneous script.
Method 2: Put everything in a single .js file, and each page loads that one file. Only one HTTP request, but each loads a lot of extraneous JavaScript (for example, the Calendar page will also be loading the script for the Gallery page AND the AJAX call page).
Assuming that proper function naming etc. is not an issue, so we don't need to be concerned about function name overlapping etc, which scenario is best for site load time and overall performance? An extra HTTP request per page, or lots of extraneous JavaScript per page?
Upvotes: 2
Views: 1262
Reputation: 733
I would do one file, and make sure your server response headers allow client-side caching. Then there is only one HTTP request for the JS file, even if they visit all the pages on your site.
Upvotes: 0
Reputation: 1616
I would serve them in one file as one HTTP request is preferable even to loading lots of JS. If it is a huge JS file, consider minification.
Upvotes: 0
Reputation: 442
It depends on the size of your Javascript and the data connection of the user, as well as the (non-)use of technologies such as HTTP2.
In general the answer is that combining separate Javascript files into a single file per page is better for performance. There's nothing to say you couldn't do this separately for each of your pages, meaning you'd have a single Javascript file with the page-specific functions, as well as the common functions you've described. You can do that manually, or use a tool like gulp to perform the task automatically.
Upvotes: 3