A good practice is to have code that is required by all pages in one file and to have specific javascript files for pages that require specific functionality. It sounds as though this is what you are doing anyway, so we have a good basis to build upon.
There are numerous ways in which you could build in what pages need what files, but remember that in normal circumstances, javascript files are cached by the browser such that those files need only downloading once.
In light of this comment
Yes, but what if you have multiple
pages with the same DOM elements? For
example, my validator() plugin is set
up like $('form').validate(), but
sometimes I don't want it to act on
all the forms on the page, only some
of them. What do I do in this case?
I suggest coming up with a convention by which to label elements common across pages that require certain jQuery plugins "attached" to them. For example, if you have a <form>
element on a number of different pages that requires a validator()
plugin, but there is more than one <form>
element on any one particular page (and not all <form>
elements should have the validator()
plugin), then I suggest using a CSS class to distinguish the <form>
elements that do need the plugin.
<!-- HTML -->
<!-- need to apply plugin to this -->
<form class="validator"> ... </form>
<!-- but not to this -->
<form> ... </form>
<script type="text/javascript">
// jQuery Code (in a separate file)
$(function() {
$('form.validator').validator();
});
</script>
That way, the plugin will be applied only to those <form>
elements matching the selector.
EDIT:
I'm not sure how the helpers in rails work, but you can pass data to an event handler in jQuery using the data
parameter of the bind()
method for any data that is not directly part of an <a>
element itself (such as an attribute like href
). If some of the links require AJAX, then it may make sense to label those with a CSS class and store the URL in the href
for the element. Then in your jQuery code that can be used on any pages that have links that make requests through AJAX, you could do something like
<a class="ajax-link" href="/get/someData.php">Data retrieved through AJAX</a>
<a href="/normalLink.php">Standard link with no AJAX</a>
<script type="text/javascript">
$('a.ajax-link').bind('click',ajaxRequest);
function ajaxRequest(e) {
e.preventDefault();
$.get(e.target.href, function(data) {
$('#loadDiv').html(data);
});
}
</script>
the link will work as per a normal link when a user has JavaScript disabled, but will make an AJAX request for data when JavaScript is enabled. I've used a named function here, ajaxRequest
as it can make it easier to debug the script (and perhaps also reuse), but you could use an anonymous function if you prefer.