I want to use Content Site Protection for my web application. If you have not heard about this, in short: this will allow me to disable any built-in javascript in my web application, helping to prevent XSS.
As a result, all my javascript codes should be in external files.
Most javascript 'library / framework' code already exists, but usually my pages contain at least a few lines of JS code, creating instances related to a specific page.
For example, I have a hypothetical registration page. At the bottom of the registration page, I have the following code:
var registrationForm = new MyApp.registrationValidator($('.regform')); registrationForm.init();
This hypothetical code receives a link to the registration form and can register the entire verification code.
Now I need to move this code to an external file. I could:
Option A : Create a small .js file for each page that only runs code for that page.
- Pros - Simple and relatively fast
- Cons is an additional js file for each page, I would prefer to minimize all my javascript in one file to reduce the number of requests.
Option B. Run all my "instance code" in a javascript file. I will simply determine if there are any .regForm 'css classes on the page and only an instance of the objects if they appear on the page.
- Pluses - one place to create an instance. The components on the page will magically start working if they have the correct css class.
- Minuses. If my application grows quite a lot, there will be a lot of initialization code, which may be unnecessary for a particular page.
Option C: Give the <body> identifier or class and execute the correct code based on a large switch.
- Pros: it can still be compressed into a single .js file, and I do not need a .js file per page.
- Cons: I suppose I feel this is a little ugly.
Overall, option B is most enjoyable if it weren't for the fact that I consider it a bad idea to have a ton of initializing code.
What I'm mostly interested in is, do you have experience in this situation and how did you solve it?