corroded
corroded

Reputation: 21584

adding .live to click functions in jquery

We have an app that uses a lot of jquery stuff and we're adding up all our scripts in an init.js file which has a lot of .live("click"), .live("hover") etc, stuff plus some if($(".classname").length) etc.

I have a suspicion it MIGHT be slowing down our pages unnecessarily(some pages don't need some scripts). But what is a more elegant solution to this? We certainly won't like a separate file for each page that needs it, that's a pain to maintain. Is there any other way to achieve this?

Upvotes: 1

Views: 110

Answers (2)

Calum
Calum

Reputation: 5316

You could use getScript to load other js files from the main one.

Upvotes: 0

ThiefMaster
ThiefMaster

Reputation: 318568

Wrap your page-specific things in functions and call the appropriate function on every page.

Another solution would be mapping URLs to functions and calling the functions applicable for the current URL automatically - then you would not need any JS on the pages itself.

For your live events you could use delegates on the body and give the body a page-specific class: $('body.page-xyz').delegate('your-live-selector', 'click', function(){...})

This only attaches an event handler if the body has the correct class.

Upvotes: 3

Related Questions