You could cache the results of processing to process less often by storing results in global variables or at least variables that persist outside the scroll callback.
There is so little in the callback to begin with that we don't have much room for improvement.
var navbar = $('#navbar');
var navborder = false;
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (!navborder && scroll >= 40) {
navborder = true;
navbar.addClass("navbar-border");
} else if(navborder && scroll < 40) {
navborder = false;
navbar.removeClass("navbar-border");
}
});
http://codepen.io/t3hpwninat0r/pen/yOvaGN
Alternatively you could disable the scroll position checking, and then set a timer to re-enable it after a short delay
var scrollTimer = 0;
$(window).scroll(function() {
clearTimeout(scrollTimer);
scrollTimer = setTimeout(function() {
var scroll = $(window).scrollTop();
var navbar = $('#navbar');
if (scroll >= 40) {
navbar.addClass("navbar-border");
} else {
navbar.removeClass("navbar-border");
}
}, 100);
});
http://codepen.io/t3hpwninat0r/pen/BKYLMb
If the user keeps scrolling, the timer keeps restarting, and the function will only run when the 100ms timer is complete. This example adds only 4 lines to your code without any other changes.
I took (read: plagiarised) the code from this answer: https://stackoverflow.com/a/14092859/1160540