Reputation: 992
I guess this is a pretty beginner question,
I know that generally you will have a 'myCustomScript.js' file on a site. But if you have lots of Javascript that is only applicable to one page or another does it make sense at all to have .. ?
sitewide.js
pageX.js
pageY.js
I just haven't really seen this before, and I wonder why (maybe because the amount of "page-specific" javascript would be negligible in most cases?). But I have 2 big chunks that are only being used on their respective pages and it seems to make sense in the interest of cutting down pageload to split them up. Bad idea?
//// EDIT /////
I think I have just seen another response that gives me the answer. "In small amounts it really doesn't matter".
So how much .js code is worth one extra request? If I have 'x' lines of code in "thisPageOnly.js' .. how many lines would that have to be to justify an extra request?
Upvotes: 3
Views: 539
Reputation: 5300
Yes, that makes sense. Eventually any big web application will have page-specific JavaScript.
To make easier maintanence of the java script files and pages, you can name-space your functions/classes that deal with siteX to be prefixed with siteX. Remember to put the includes for site-specific js at the bottom of the html-output.
A reason for why you might not have seen it is that when you name-space your js you could add it all in one js file and obfuscate or minimize that. If you have 10-20 page-specific js files, you will make 10-20 requests which is not that good, so you have page-specific js content but including it once. And the way to do that is to name-space correctly for each page.
Have you learned about prototypes and namespacing yet?
Like this:
var yourPageNameSpace = {
func1: function () {},
func2: function() {}
}
then you do yourPageNameSpace.func1()
So in short. Yes that is okay for one or two pages, but not for each and every page you have. Consider namespaces in that situation.
Upvotes: 2