Ter*_*rry 8 html javascript performance jquery function
我试图在以疯狂的速度创建多个DIV时找出有关性能的最佳实践.例如,在每个.mousemove事件中......
$('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);
});
Run Code Online (Sandbox Code Playgroud)
所以,这一切都很好用,但它的效率很低(尤其是当我尝试填充每个鼠标移动位置之间的空间时).这是一个例子......
$('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);
});
Run Code Online (Sandbox Code Playgroud)
我真的无法弄清楚如何改善事物.相信我,我已经尝试过研究,但它没有做太多好事......我正在寻找的是一些建议,例子或更好实践的链接......
请注意我正在自学代码.我是一名平面设计专业的学生,这就是我在课堂上度过夏天的过程......制作小项目来自学JavasSript,有趣的东西:)
鼠标踪迹,更多元素 - 非常慢的
鼠标踪迹,更少的元素 - 非常慢的
鼠标踪迹,光秃秃的骨头 - 慢
这里存在多种不良做法:
这里的根本问题实际上是使用元素而不是画布。解决这个问题后,与 DOM 的交互应该变得最少,从而也解决了其他问题。
此外,那些声称这工作正常的人并没有检查他们的 CPU 使用情况。在我的 Core I5-2500K 上,一个核心立即被最大化,这对于像在屏幕上渲染鼠标轨迹这样的小事情来说是荒谬且不可接受的。我可以很好地想象这在旧计算机上会非常非常慢。所以是的,它很顺利,但代价是使用足够的资源来让 10-20 个以上的选项卡正确地执行相同的操作。
当我快速移动鼠标时,这会占用 7-14% 的 cpu,这会占用 25%。
归档时间: |
|
查看次数: |
733 次 |
最近记录: |