Many Javascripts How to Divide Load

Let’s take this website as an example: There are multiple calculators on this website, and each calculator has its own unique page. Based on my understanding, it would be wise to have JavaScript (JS) affiliated with the HTML and CSS of each calculator load on its respective page. However, this approach would result in numerous JS files, making the project difficult to manage since each page would require a separate call to a unique JS file.

Alternatively, if all the JS for these calculators is written on one page, it would create a bulky page.

Any solution or advice to handle such Projects?

Depends a bit on what you value for your determination of “solution”.

A script block in the HTML. Can be a bit of a tracking nightmare for the coders on bigger projects or if you want to share common code between pages, but it removes extra calls to the server and delivers just the code required to execute the page.

Individual JS files for each page: Close to the before, but it at least separates the JS from the HTML in the file structure.

Individual JS files for each page + includes: If you’re doing a lot of code-sharing, it might be worthwhile, but only for the most bulky of projects.

One Big Bulk JS: Probably not recommended because you’re now including unneeded Javascript, but with current speeds of internet around the world and the relatively small size of most JS, you’re not going to notice it. Means you’ve got no problems with making sure you loaded the right functions though; you’ve got all or none of them.

You’ll probably notice that i’m not giving a definitive answer. Because there isnt one really.

1 Like

Also, with the right cache headers, browsers only need to download it once. After that if people browse away to other pages there is no need for them to download any additional js files because they already got everything they need.

So I guess it depends on whether you expect a typical user to only visit exactly one page (then it will be better to have one js per page) or multiple pages (then it might be better to have everything in one big js file - operative word being might).

1 Like

That’s why I propose to make each js file as small as possible. So the browser loads only what is needed on the first page and takes it out of the caches on reuse or load new scripts if you switch to new content.

1 Like

There is another tradeoff at play though. Which is that requesting a file takes considerable overhead when compared to just downloading a larger file - that is, once a connection had been established, transfer is cheap.

So one file of 200kb may be better than two files of 70kb, in terms of total time spent to download.

1 Like

Thanks, everyone for the in-depth insight.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.