NOTE: I have now created a jQuery plugin which is my attempt of a solution to this issue. I am sure that it could be improved and i\'ve probably overlooked lots of use c
First I put specific classes on the body or on specific containers e.g. articles
, form-validation
, password-meter
, … . If I have an MVC app, I prefer to put the controller name into a body class. This does not hurt a lot and can be useful for styling, too.
Then on each document.ready block I check for the existence of such a class, and if it does not exist I return from this function. This approach is simpler as it does not have the main code inside an if clause. This approach resembles to assertions that are used to check prerequisites of a function.
Example:
$(function(){
if($('body').hasClass('articles') === false){ return; }
//body of the articles code
});
$(function(){
if($('body').hasClass('password-meter') === false){ return; }
//include password meter in page
});
The bonus of this approach is that no unwanted code can sneak into a ready callback, which makes it easier to reuse. The downside is that you get many callback blocks and if you do not pay attention duplicate code can easily sneak into your app.