scroll handler optimization

JavaScript performance comparison

Test case created

Preparation code

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
Original
$(function() {
  var up = $('#horiz_line').offset().top + $('#horiz_line').height() + 25,
      triga = $('.trigger');
  triga.css("display", "none");
  $(window).scroll(function() {
    var down = $(this).scrollTop();
    (down > up) ? triga.fadeIn('fast') : triga.fadeOut('fast')
  });
});
pending…
Modified
$(function() {
      //cache non-changing elements and values
  var horizLine = $('#horiz_line')
    , up = horizLine.offset().top + horizLine.height() + 25
    , triga = $('.trigger')
    , $window = $(window)
    ;

  triga.css('display', 'none');

  //we cached window wrapped in jQuery earlier so we reuse it
  $window.scroll(function(){
    //omitting down variable since it was only used once
    ($window.scrollTop() > up) ? triga.fadeIn('fast') : triga.fadeOut('fast')
  });

});
pending…

You can edit these tests or add even more tests to this page by appending /edit to the URL.

Compare results of other browsers

0 comments

Add a comment