0

I have one .js file for the whole website, in some places in the code I put $(document).on event inside if condition to make the event only available in certain pages.

example:

if( $(".some-class").length )
{
    $(document).on("click",".some-button",function(){
    ......
    });
}

The code runs fine, but I am worried if this is bad practice? or if it will cause bugs on some older browsers?

I don't think there will be any benefit to performance from what I did, but if it is not harmful then I want to keep it, because it will be difficult to run over all the code to change it.

DeepBlue
  • 684
  • 7
  • 23
  • I'm not sure I understand the question. Can you explain *why* you think this might be a bad practice or cause bugs on older browsers? – user94559 Aug 01 '17 at 11:21
  • I read that it is bad to declare function inside if condition, because it will cause unpredictable behavior, I am not sure about that though – DeepBlue Aug 01 '17 at 11:27
  • No it won't cause unpredictable behavior but at same time it doesn't seem you need to delegate it either if you are only concerned with existing elements – charlietfl Aug 01 '17 at 11:28
  • "I read that it is bad to declare function inside if condition, because it will cause unpredictable behavior..." Where did you read that? – user94559 Aug 01 '17 at 11:29
  • Here: https://stackoverflow.com/questions/10069204/function-declarations-inside-if-else-statements – DeepBlue Aug 01 '17 at 11:34
  • That question doesn't apply here. You're creating an anonymous function, so there's no function hoisting and no reference to the function outside of the `if` statement. – user94559 Aug 01 '17 at 11:38
  • BTW, I have no idea why this was closed as a duplicate of that particular question. It seems utterly unrelated. – user94559 Aug 01 '17 at 11:40

0 Answers0