I am working on a medium size web site that has plenty of custom JavaScript written for it.
At present all the script is stored in seperate JS files for each area of functionality. These are then minified and combined into a single, large JS file during our build process.
For each page, the relevant JavaScript is usually executed based on the presence of an element with a particular class on the page. For example:
$(document).ready(function()
{
var foo = $("div.dostufftome")
if(foo)
{
// dostuff
}
}
I’m concerned that this approach seems a little fragile, and also potentially quite slow.
The only other alternative I can see is to put the ‘activation’ code inline in the HTML in a CData section, with the bulk of the code in the attached JS file.
Grateful for any advice.
If you’re concerned about performance, it’s better to trigger behavior off of elements with “id” values. In my experience, unless there are many hundreds of such checks that your code needs to make, there’s no noticeable performance drag.
You can possibly help even more by having more than one level of check. Give some pages with relatively unique needs a special class on the body tag, and then you can nest a bunch of tests within a test for that class. That way, pages that can be ruled out for some Javascript functionality will only require a single check.