I can't put this comment where I actually want it, but put this code at the end of the file (as per my suggestion below):

    $(function() {
        if($('.aggstats').length() > 0) {
            getStats();
        }
    });