1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

Overhead of listeners

Discussion in 'jQuery' started by sarahk, Sep 21, 2016.

  1. #1
    I have a bunch of listeners coded in a single javascript file and they're pretty much active all the time on all pages. This is pretty harmless if the listeners have nothing to listen to but there will be a performance overhead.

    Alternatively, I can check to see what page the user is on and only create the listener if it's the right kind of page. Aside from human error maintenance issues there will be an overhead on this too.

    Has anyone delved into this and worked out which approach is best?
    SEMrush
     
    sarahk, Sep 21, 2016 IP
    SEMrush
  2. digitalpoint

    digitalpoint Overlord of no one Staff

    Messages:
    38,278
    Likes Received:
    2,599
    Best Answers:
    460
    Trophy Points:
    710
    Digital Goods:
    29
    #2
    Generally, I find that adding listeners based on a selector that isn't page specific (but rather object specific related to the object you want to listen for) is the way to go.

    For example, if you look at the source code of any page here, anything with the class "OverlayTrigger" has a listener to that intercepts the mouse click (usually a link) and instead fires an AJAX that gives you a page overlay (as an example, when you click on the user avatar here in this thread).

    By using selectors, you will check if the object is on the page, and if it is, bind the listener, if it's not... nothing.
     
    digitalpoint, Sep 21, 2016 IP
  3. sarahk

    sarahk iTamer Staff

    Messages:
    25,188
    Likes Received:
    3,428
    Best Answers:
    100
    Trophy Points:
    665
    #3
    That makes sense. The method I've actually been using is to check the length of the type of object and then add the related listeners - if a exists then b and c will too, type of thing.

    if ( $( "#myDiv" ).length )
    Code (markup):
     
    sarahk, Sep 21, 2016 IP
  4. digitalpoint

    digitalpoint Overlord of no one Staff

    Messages:
    38,278
    Likes Received:
    2,599
    Best Answers:
    460
    Trophy Points:
    710
    Digital Goods:
    29
    #4
    Ya that works too... internally with jQuery though it's basically the same thing.
     
    digitalpoint, Sep 22, 2016 IP