Listeners: OK to run on every page, or initialize only on pages that need them?
On my site, I have elements with "event listeners" (.live, .bind, or .delegate) and I can divide these into groups based on how often they appear:
- Elements that are on every page.
- Elements that are on some pages.
If I have an element that is on every page, and that element requires a listener, then of course I just implement that listener site-wide.
I'm trying to figure out what that will be wisest for an element that both (a) appears only on a few pages, and (b) requires a listener:
- Implement the listener site-wide
- Implement the listener so that it must first be initialized on any page that wants to use it
For example, say I have
<input class='autocomplete' />
th开发者_如何学Cat appears on several pages, but not site-wide. When someone enters text, it hits the database and tries to complete their query for them.
Since this element doesn't appear on every page, is the overhead of jQuery.live('someEventsHere',MyHandler())
high enough that I should only call it on pages where it is used? (E.g., by creating an initializeMyHandler()
function and calling it on those pages?) Or, on pages where that listener will not be used, is this cheap enough to set anyway and not worry?
live()
works by attaching your event handler to the document, not to the element. Thus, live()
makes use of event bubbling, so attaching event handlers won't incur that much overhead, though there will admittedly be some. The HTTP request for the inclusion of a JavaScript file is more than the overhead incurred from attaching an unused event handler to the document.
You will incur overhead from live() since it has to keep checking for elements whenever the DOM changes. Depending on your site traffic, this may be acceptable to you.
However, I'd say separate your code into files and include only the files you need on each page.
精彩评论