Skip to content Skip to sidebar Skip to footer

Javascript Animate Performance

I'm having some issues here with my js. It functions correctly, but the performance is too slow in a certain case. I scroll to the bottom softly, but when I try to scroll up agai

Solution 1:

You're not caching selectors in your animation (and repeatedly using $(this) or $('#mask') is wasteful as well), so every time the user scrolls, it's /searching the entire dom/ for #content, #illusion1. Also, animating on scroll is somewhat redundant, since scrolling is a kind of "animation" itself. Fixed positioning would be ideal, but you can achieve the same effect by just setting the CSS style on each scroll. Just don't use animate on every scroll event. Also, you're not supplying 'px' for left and top and doing so prevents the need to "cast" into a string by prepending "-"+. Try re-writing the $(window).scroll function like so:

var$window = $(window),
    $content = $("#content"),
    $illusion = $(".illusion1");
$window.scroll(function(){ 
    var curScrollTop = $window.scrollTop();
    var angleVar = windowScrollX/windowScrollY;
    $content.css({ left: (-curScrollTop*angleVar)+'px', top: (-curScrollTop)+'px' });
    $illusion.css({ left: (-curScrollTop*angleVar*0.5)+'px', top: (-curScrollTop*0.5)+'px' });
});

If your heart is set on the animation effect, consider a debounce/throttle method. Rather than animating on every single scroll event, use: "timeout = setTimeout(function(){ ... }, 25)" that will perform the animation when the timeout is allowed to expire, and on scroll simply clearTimeout(timeout) and set the timeout again. The animation will not be realtime, as it will never be performed unless the user stops scrolling for 25ms.

Solution 2:

Not sure if this will help, but when I have to move an element relative to the browser window on scroll, I use some form of fixed positioning. I've found this gives better performance in Chrome and other browsers than trying to set or animate the offset of absolutely or relatively positioned elements. Perhaps if you could whip up a jsfiddle which illustrates the effect you are trying to achieve I could give some further advice.

EDIT: If you could provide some of the HTML in lieu of a jsfiddle that would also be helpful.

Solution 3:

I would say to change the whole bundle to TweenLite, which runs smoother than jQuery for animations.

http://www.greensock.com/v12/

you can compare the difference below.

http://www.greensock.com/js/speed.html

Post a Comment for "Javascript Animate Performance"