@EthanBierlein Made a really good point, but he forgot something important.
It's always a good idea to wrap your code on an anonymous function:
(function ($) {
$(document).ready(function () {
[code]
});
})(window.jQuery);
This prevents problems in case you run jQuery.noConflict()
before, but you forget it.
You have the following code block:
$(window).scroll(function (event) {
var scroll_positon = $(window).scrollTop();
$.cookie('prev_scroll_position', scroll_positon, { expires: 7, path: '/' });
});
Instead of this, consider wrapping the $.cookie
call in a setTimeout
:
$(window).scroll(function (event) {
var scroll_positon = $(window).scrollTop();
setTimeout(function () {
$.cookie('prev_scroll_position', scroll_positon, { expires: 7, path: '/' });
}, 10);
});
This won't block the scroll
event, which may improve UI responsiveness.
Why is that? The scroll
event may be triggered multiple times a second, and that setTimeout
schedules the cookie writting to a time that the browser is free.
Or that has some time for writing the cookie.
You should experiment with it.
Update!
As @Pevara pointed out in the comment section, this is not 100% a good idea.
He suggests to use a clearTimeout
. From there, I could infer what he was trying to say.
Still follow the advice to use a setTimeout
, but with a bigger delay (as he suggested: 250ms).
But now, the twist:
var timeout;
$(window).scroll(function (event) {
var scroll_positon = $(window).scrollTop();
clearTimeout(timeout); //clear it to avoid crazy writing
//and create a new interval to write it later
timeout = setTimeout(function () {
$.cookie('prev_scroll_position', scroll_positon, { expires: 7, path: '/' });
}, 250);
});
This will eliminate all the craziness of writing cookies like mad! And will write it only once, saving the browser from re-re-re-re-writing it.
debounce
function, so the scroll function wont be called for every pixel, but after scrolling has stopped for Xms - davidwalsh.name/javascript-debounce-function. This will prevent the scroll-function to be a bottleneck while scrolling \$\endgroup\$