Concatenate each javascript page into one file, or serve up page related files?

Let's say I have a site with 26 different pages, A.html through Z.html, and each page uses different JavaScript files, A.js through Z.js. I have two options and I am wondering if anyone has any suggestions on which is better.

Option 1 . In the build step, combine all 26 JS files into one file, all.js, and include all.js on each page.

Pros : - After all.js is cached, it is cached for every page, not just the current page. This reduces the HTTP request not only for subsequent views of the current page, but also for every page on the site, even pages the user has not yet visited.

cons : - all.js will, on average, be 25 times larger than it should be because it will have a lot of JavaScript that will never run on any given page. - Any change to A.js via Z.js means that all.js will be changed, which means that the cached version needs to be replaced.

Option 2 . On each page, upload only the file. So on A.html, only include A.js, on B.html, only include B.js, etc.

Pros : - Download only the required js file, that is, the file will be as small as possible. - Changing to A.js will only affect users when they visit A.html. B.html-Z.html will not be affected.

Cons : - The user will have to download each js file separately. So when they visit A.html they will only be cached by A.js. And then when they visit B.html they will need to download B.js etc.

There are pros and cons to each approach, so I'm looking for help in determining which approach is superior.

+3


source to share


2 answers


Both approaches seem to be a work-around to me, but I'll probably go with option 2 simply because the performance will be lower in the beginning and you only download what you need. It is like choosing between paying off a debt with a 0% share at the same time or several monthly installments. I will obviously pay on a monthly basis because I want to keep the liquid for as long as possible (plus I want inflation to work in my favor). In this case, if the user doesn't load certain pages, you end up not paying the "debt." But I wouldn't go against combining everything into one file, again, because the performance, even large, should be negligible unless you are building a monster.



Whichever approach you choose, consider merging and minifying your files, not just JavaScript, but also CSS and images (use sprites whenever possible)

+1


source


The accepted best practice over the years is to bundle all of your assets into the smallest possible number of files and minify / compress the resulting files.

You have to do this with your JavaScript, CSS and images as sprites.



The benefit of minifying HTTP requests far outweighs including a few extra kilobytes of JavaScript or CSS, or image data that has been unnecessarily included in every page.

-2


source







All Articles