Question

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.

Was it helpful?

Solution

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.)

OTHER TIPS

If they're a bunch of small scripts, just roll them into one. Loading a few small files is slower than loading one file with equal size. The sum of size of all the files might be even smaller if they're compressed (i.e. by the http server). It's easier for both the server and the clients to use one file.

Another consideration is, sometimes we put random bits in script file name so browsers see it as a different file from the cached one. Having one file makes it easier to manage this too.

Another consideration is maintenance. If you have code in 10 files, that's 10 files you have to check in order to make one change.

Re lazyloading: that's an extra file that has to be loaded (the jquery plug-in)? How big? Why would you want to add code that probably isn't necessary. For example, you could pre-load the first 5-6 images with your HTML, then include the rest once the page has loaded/rendered.

If you're really worried about load times, try both...time it.

Licensed under: CC-BY-SA with attribution
scroll top