If on a website, only one page uses a javascript file, should it be loaded on all pages?

169 views Asked by At

This question has been running through my head for quite a while. If for example only the index page uses a carousel, does it make sense to include it on all the pages? For me it doesn't, but most of the WordPress plugins and themes don't take this into consideration, and they load the scripts on all pages. Is there something I am missing?

Furthermore, while I was reading Grunt's minifying process, it concatenates all the scripts used on the site altogether then minifies them, which in fact includes any and all the javascript including the ones used only on one page. Is that efficient? Grunt for People Who Think Things Like Grunt are Weird and Har. Is compressing makes up for all the extra codes being used?

4

There are 4 answers

1
Diodeus - James MacFarlane On

It doesn't really matter because after the first page load the JS file will be cached on the browser anyway.

0
DrCord On

If you can reasonably do so you should only load the scripts onto the page(s) where they are needed, if for no other reason than code cleanliness. Plugins and such for WordPress (or other pieces of software) do not know where they will be needed so they have to be available everywhere.

0
Brad On

If you only need something in one place, only include it in one place. Most WordPress plugins and themes don't take performance into consideration at all.

The argument for compiling all of your JavaScript into one file is that it is downloaded once, and cached, and you're good to go. This makes perfect sense for common code used throughout your site. This is useful for things used frequently, or even things that you know will always be downloaded. For instance, if you know your home page is your primary landing page 90% of the time, and the overhead of an extra request makes it worth it, go ahead and bundle it in.

0
ryudice On

As long as you are doing caching the right way (probably using ETags), it doesnt really matter, having to do a new web request to get each page scripts would probably be worst, because if your homepage contains all your scripts, then any other page the user visits wont have to fetch new scripts.