I'm using bits of javascript on my website for an image gallery, smooth scrolling, etc. These scripts are not used on every page (not every page has an image gallery for example). However, the scripts aren't very big and most users will have to download them eventually (the image gallery is very central to the website).Now what would be the pros and cons of these two (mutually exclusive) ways of including the scripts:add them to every page (so that they'll all be cached after one page view)add them only on the pages on which they are used (so they're cached only when they're needed, but some pages will take a little longer)?I'm not asking for opinions, I'd just like to know if there are any pros and cons I've overlooked.
Add javascript to all pages (for caching), or only to the pages that require the scripts (for a smaller page size)?
web development;javascript;performance;speed;caching
I do not know what considerations you have made.  My recommend would be that you load into each page only what you need to load that page.  And then lazy load everything.  Make the lazy loading something you can switch on and off easily.This will make initial page load as fast as possible on the first page you encounter.  The lazy loading will speed up the second page load.  And you can QA with lazy loading off to be sure that everything that is needed for a page is actually loaded.  (Else it would be easy to miss the fact that a user could get JavaScript errors because they are trying to interact with something that hits a library that isn't there yet.)