I alway have a case where I have one .js file which contain event handlers for many pages in my website, something like this:
$(function () {
$('#my-textbox1').click(function(){ doSomthing(); }) //--> this my-textbox1 exists in page example1.aspx
$('#my-textbox2').click(function(){ doSomthing(); }) //--> this my-textbox2 exists in page example2.aspx
});
Now suppose the user opened page example1.aspx, jquery will search for my-textbox1 and if found it will attach a click event to it, then will search for my-textbox2 and will not find it and will not attach the event.
But like this jquery in all cases will search for my-textbox2 in all pages,
What I want to know is the best practice you do to avoid unwanted selectors to get called in pages that don't want them.
May be it is not a big problem with 2 events, but suppose i have hundreds of events want to attach, this will affect the page load performance for sure.
In our projects, we always use a view pattern based on body classes. Here is a stipped down example:
views = {
home: function() {
// do stuff on home page
},
products: function() {
// do other stuff on products page
}
};
$.each(document.body.className.split(' '), function() {
if (this in views) {
views[this]();
}
});
$(function() {
var pn = window.location.pathname;
if (/example1/.test(pn)) {
$('#my-textbox1').click(function(){ doSomthing(); });
}
if (/example2/.test(pn)) {
$('#my-textbox2').click(function(){ doSomthing(); });
}
});
Im not sure how good this solution is. Im just making it as i go.
First. you could probably decorate your javascript with some comments like so
//[all]
$(function () {
//[example1.aspx]
$('#my-textbox1').click(function(){ doSomthing(); }) //--> this my-textbox1 exists in page example1.aspx
//[/example1.aspx]
//[example2.aspx]
$('#my-textbox2').click(function(){ doSomthing(); }) //--> this my-textbox2 exists in page example2.aspx
//[example2.aspx]
});
//[/all]
Second: Get ur JS file served via an aspx page(it can also be done w/o using this way - using httphandlers)
e.g.
The CodeBehind for GetJS.aspx will read ur actual js file from disk into memory.
Then Look at the value of Referer from the request headers(which will be pointing to the page that has requested GetJS.aspx (in our case it will be either example1.aspx or example2.aspx).
Now that we know which page has requested the JS we can strip its contents according to the comment decorations //[all],//[example1.aspx], etc and do a response.writefile with the appropriate content-type.