I am trying to figure out best practices regarding performance when creating multiple DIVs at insane speeds. For example, on every .mousemove event ...
$('head').append("<style>.draw {width: 20px; height: 20px; position:fixed;</style>"); $(document).mousemove(function(mouseMOVE) { //current mouse position var mouseXcurrent = mouseMOVE.pageX; var mouseYcurrent = mouseMOVE.pageY; //function to create div function mouseTRAIL(mouseX, mouseY, COLOR) { $('body').append("<div class='draw' style='top:" + mouseY + "px; left:" + mouseX + "px; background: " + COLOR + ";'></div>"); } // function call to create <div> at current mouse positiion mouseTRAIL(mouseXcurrent, mouseYcurrent, '#00F'); // Remove <div> setTimeout(function() { $('.draw:first-child').remove(); }, 250); });
So, this works all well and dandy, but it is mega inefficient (especially when I try to fill the space between each position of mouse movement). Here is an example ...
$('head').append("<style>.draw {width: 20px; height: 20px; position:fixed;</style>"); $(document).mousemove(function(mouseMOVE) { //current mouse position var mouseXcurrent = mouseMOVE.pageX; var mouseYcurrent = mouseMOVE.pageY; // function to create div function mouseTRAIL(mouseX, mouseY, COLOR) { $('body').append("<div class='draw' style='top:" + mouseY + "px; left:" + mouseX + "px; background: " + COLOR + ";'></div>"); } // function call to create <div> at current mouse positiion mouseTRAIL(mouseXcurrent, mouseYcurrent, '#00F'); // variabls to calculate position between current and last mouse position var num = ($('.draw').length) - 3; var mouseXold = parseInt($('.draw:eq(' + num + ')').css('left'), 10); var mouseYold = parseInt($('.draw:eq(' + num + ')').css('top'), 10); var mouseXfill = (mouseXcurrent + mouseXold) / 2; var mouseYfill = (mouseYcurrent + mouseYold) / 2; // if first and last mouse postion exist, function call to create a div between them if ($('.draw').length > 2) { mouseTRAIL(mouseXfill, mouseYfill, '#F80'); } // Remove <div> setTimeout(function() { $('.draw:first-child').remove(); $('.draw:nth-child(2)').remove(); }, 250); });
I really cannot understand how to improve the situation. Believe me, Ive tried to research, but he did not do much good ... What I'm looking for are some suggestions, examples or links to best practices ...
Please note that I teach the code. I am a graphic design student, and this is how I spent my summer outside the classroom ... Doing small projects to teach myself JavasSript, fun stuff :)
Ive created some jsfiddles to show that Im working on ...
Mouse track, additional items - Very slow •
Mouse, fewer items - very slow
Muscle Track, Bare Bones - Slow
performance javascript function jquery html
Terry
source share