1

I have an MVC application that utilizes ajax in order to fetch some data from the server and/or load partials. This is what I do in order to bind action to an element that doesn't necessarily exists on the page:

$(document).on("click",".helloWorld", function(){ alert("hello world") });

Is it a bad practice not to bind action directly to the element? In this case, should I have scripts directly on partial pages? Is it much slower? Can it sabotage performance if I have a dozen of similar methods on the page?

Vadims Samsinovs
  • 114
  • 1
  • 12
  • [This answer](http://stackoverflow.com/a/12824698/1612146) should help you understand a little better. – George Sep 22 '15 at 15:32
  • 1
    The speed decrease is near if not completely unperceivable. You're doing event delegation, so this assumes that `.helloworld` is a dynamically created element. If it's not, you can do a simple non-delegated event. – Sterling Archer Sep 22 '15 at 15:33

2 Answers2

2

There is no better way than delegate if the elements don't previously exist in the page (say, they are loaded later or replaced) since they can't be bound

Performancewise, it's actually far more performant than binding to many elements. An use case for event delegation would be a really big table with lots of td. Even if all elements are there beforehand, it's faster for the table to handle the events of the td's

I'd say you are ok. In your case, your content is dynamic so I'd say you can't do differently(although I haven't seen your code, so cant say for sure)

JSelser
  • 3,510
  • 1
  • 19
  • 40
1

I think it's OK. The computer nowadays is quite fast, so some more javascript code is not a big problem. The only thing make your website slower is that "more code means more time for page load". But it's not very much. So don't worry too much about it!

Dat Tran
  • 1,576
  • 1
  • 12
  • 16