I want to use Content Site Protection for my web application. If you haven't heard of it, in short: it will allow me to disable any embedded javascript into my web app, helping preventing XSS.
The result is, all my javascript code will have to be in external files.
Most javascript 'library/framework' code already is, but usually my pages will contain at least a few lines of JS code, instantiating components that are relevant to a specific page.
For example, I have a hypothetical registration page. On the bottom of the registration page, I have the following code:
var registrationForm = new MyApp.registrationValidator($('.regform'));
registrationForm.init();
This hypothetical code gets a reference to the registration form, and could register all the validation code.
Now I have to move this code to an external file. I could:
Option A: create a small .js file for every page, that only executes code specific for that page.
Option B: Execute all my 'instantiating code' in a javascript file. I'll just detect if there's any '.regForm' css classes on the page and only instantiate my objects if they appear on the page.
Option C: Give my <body>
tag an id or class, and execute the correct code based on a big switch.
All in all, Option B is the nicest, if it weren't for the fact that I feel it's a bad idea to have a ton of initializing code.
What I'm mainly wondering is, do you have experiences with this situation, and how did you solve it?
Option D (Variant of A and B): Have a look at deployment systems which will compile (and minify) multiple javascript source files into one, taking only the required files for that page into account.
For PHP, Assetic is such a system.
if you are willing to use a framework like jQuery (to dynamically load and execute external javascript), you could have the benefits of A and B combined. every page would load the same .js, which determines (by presence or absence of dom elements) which other .js files to load dynamically.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With