Where to insert script blocks
The dilemma is this:
If I try to put all the script blocks on the master page (including the page in some frames), each page gets a copy of every script (including the ones they don't need) and they quickly add up and bloat to the page size.
If I include / insert script blocks where needed, the javascript is propagated throughout the project.
I struggle to maintain the right balance. Anyone?
a source to share
We minify, merge and gzip our JS site (actually about 17 files are merged into two files, one for all of our code and one for library code like mootools and clientcide). This significantly reduces the loading times for scripts. Compression and merging are done and fly and cached on the server so development doesn't slow down at all. Our total JS for sitewide attributes is around 50K once everything is compressed as above.
We also set long expiration times on files, all of which have a version number, so when we make changes, we increase the version number (we have a strong point to make it easier), and users are forced to get fresh versions after downloads they are cached by the browser.
In addition, we took a step to put our JS in the page footer, this makes things much faster and gives the user a chance to see when we load the JS.
Some individual pages have one script they need (search forms, etc.), they get the same treatment as above (i.e. all necessary files must be merged, minified, gzipped), but the code is the side remains the same we can use caching. So in this case we could load 3 JS files, sitewide, library and special code for this page.
a source to share
Including all JS files is not a major issue (unless they have slow code running on load) and will not bloat the page much: after they are loaded, the browser will cache them anyway, so this will result in 0 load times on the following pages ...
Until you put the content of the JS files on the page itself, of course! :-)
a source to share
If inflating your page size is a concern, perhaps you should move your Javascript into a separate js file (or even multiple ones) that are referenced by pages that need it. This means you will have more HTTP requests for visitors the first time, but it will allow the browser to cache the Javascript so that it doesn't need to run it again for every page on your site.
a source to share
I would extract as much JavaScript for external files as possible .js
. Include the most commonly used libraries on the main page, but if any particular page needs JavaScript specific to that page, I would suggest loading it on this page only. Keep a cross-reference of which files .js
are being loaded on which pages, and if you see the library linking to a large number of pages, move it to the master page.
Make sure to compress / minify all your external JavaScript libraries using something like YUI Compressor or some other tool mentioned in What do you use to minify and compress JavaScript libraries? ...
a source to share