jQuery Optimization/Best Practices

I’ll try to answer these as concisely as possible:

  1. Cache it when it’s used often, especially in a loop situation, running the same code to get the same result is never a good thing for performance, cache it.

  2. Use this when you only need a DOM element and $(this) when you need the jQuery methods (that wouldn’t be available otherwise), your example of this.id vs $(this).attr("id") is perfect, some more common examples:

    • Use this.checked instead of $(this).is(':checked')
    • Use $.data(this, 'thing') instead of $(this).data('thing')
    • Any other case where creating a jQuery object isn’t useful basically.
  3. Decending from an ID selector is preferred for performance…how specific do you need to be? That completely depends, in short: be as specific as you need to be.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)