The best overall result is often achieved by creating a code library that can be accessed by all of your pages in a single minified external JS file. Then enter the page initialization code, either embedded with the page, or in an external JS file specifically for this page.
This has the following advantages:
- You have only one copy of all your functions, which makes it easier to maintain.
- A single minified external JS file can be very efficiently cached by the browser. It will load from the first page that the viewer sees, and from that moment it will be sent from the browser cache.
- You only use the initialization code that is appropriate for the particular page displayed. If you mix all your initialization code and just let a lot of them fail, because in fact for other pages you can quickly create a big mess on a large site, you could achieve quite high performance by performing all these initialization functions and looking for DOM objects that are not there.
- It is much easier to debug if only those initializing functions that should work are working.
- With external JS in one cached external file, you can minimize the number of external files that need to be loaded if the initialization code for a particular page is included in the line on the actual web page and not in its own external JS file. For maximum page rendering performance, this should be after the HTML page.
For further optimizations in a large project, if the external JS file is very large, and you have a large classification of functions that are needed only in one part of the site, then you can split them into another external JS file, which is included only in this part of the site. Since these files are effectively cached by the browser, the main savings are analyzing the parsing time and the amount of memory that may or may not be significant (this depends on how large the project is). There is usually a practical limit to these optimizations, since downloading multiple external JS files usually takes longer than downloading one larger one.
Be sure to specify the version number of your external JS files, so when you change them, the file name changes, so browsers are forced to retrieve the new version and not get stuck in the old version from the cache.
source share