I have a question regarding animations via javascript in HTML using DOM. In this case I am using a with absolute possition and css + jQuery and animate the div.
So when I run through my big array of positions x,y the animation runs very slow. I am running at 100ms (80ms) Interval, but it seems that the rendering is not fast enough and my animations takes longer than 10 seconds…
When re-running the animation it seems that the instructions have been somehow cached ( Rendering ) and my animations runs just perfect.
Then again if I wait for lets say 5 mins, it will be slow again. ( Seems to be low level machine code memory which has been deleted, because it was not used again? )
I just cant figure out how to let my animation run smooth, if its executed the first time.
I tried fabric.js to render animations… Same problem. At the first run its slow. Second run and following are smooth.
function render_mouse()
{
if(play_pos < mousefile_length)
{
$('.mouse').remove();
$("body").append(
$('<div id="mouse" class="mouse"></div>')
.css('position', 'absolute')
.css('top', play_mousefile[play_pos+1] + 'px')
.css('left', play_mousefile[play_pos] + 'px')
.css('width', mousesize)
.css('height', mousesize)
.css('background-image', 'url(images/cursor.png')
);
play_pos = play_pos +2;
}
else {
clearInterval(play_mousetimer);
}
}
UPDATED:
$('#mouse').animate({
left: rec_mousefile[play_pos]+"px",
top : rec_mousefile[play_pos+1]+"px"
},80);
The animation would be faster if you didn’t do so many operations on the mouse div every time.
Basically, append the mouse to the dom once, with all the CSS needed for the initial render, cache the reference to the appended element, and then manipulate ONLY the css properties necessary for the animation.
By keeping the element in the dom, rather than removing and re-appending each time, you should see a bit of a performance increase. Further, saving a reference to the appended element will prevent you from having to re-query the dom before giving another update.
The animation should always be a bit faster on a second run due to caching, but these optimizations should help the initial run at least a bit.
** edit in response to comment **
You could cache the reference to the mouse div outside the function, or hang it off the render function itself, a la:
var mouseDiv = $(‘#mouse’);
or