jQuery Mousemove and performance question
I've just wrote some code (and it works) for displaying some text near the mouse when the mouse is on any of 4 rectangles (different text for different rectangle). I used html tag < map >< /map>, css and jquery. Everything works fine. I don't like 100% CPU Usage开发者_如何学编程 when mouse is moving on the picture.
This is a jquery part:
$('area').each(function(){
var area = $(this),
alt = area.attr('alt');
area.mousemove(function(event){
var tPosX = event.pageX +10;
var tPosY = event.pageY - 85;
$('#rectangletext').css({top: tPosY, left: tPosX});
$('#rectangletext').html(alt);
}).mouseleave(function(){
$('#rectangletext').html('');
});
});
I've tested it in IE, FF, Chrome and Opera (at the same time, on the same computer). Area.mousemove eats up to 100% CPU when you move your mouse on that . The question is: how to reduce resources that are needed when you move your mouse on that map? IE is the worst - CPU Usage jumps up to 100%. FF eats about 67%-100%. Opera eats less than 62% (never more than 62%). Chrome is the best: average is about 28%, maximum is 42%.
It's OK to reposition text to be near the mouse not every millisecond, but every 300 milliseconds, if it helps to reduce the resources that are required. How to do that? Any better solution for this problem than to use mouseenter instead of mousemove? The cons of mouseenter is it doesn't update the position of the popup text until mouseleave is called.
Thank you.
You can keep track of the time your mouse last moved.
var prevDate; // keep this as a global variable
// put the following inside the mousemove function
var date = new Date().getTime();
if(date - prevDate > 300){
// your code goes here
prevDate = date;
}
You could start an interval on mouseenter and update the position in there. Play around with the interval time to find a good frequency. Also storing the jquery objects in a variable could help a bit, but not much since you're accessing them via ID which is pretty fast.
Setting the html is pretty expensive, and you only really need to do it on mouseenter. Moving your selectors outside of the loop will also give you a nice speedup.
var $rectText = $("#rectangletext");
$('area').each(function(){
var area = $(this),
alt = area.attr('alt');
area.mousemove(function(event){
var tPosX = event.pageX +10;
var tPosY = event.pageY - 85;
$rectText.css({top: tPosY, left: tPosX});
}).mouseenter(function(){
$rectText.html(alt);
}).mouseleave(function(){
$rectText.html('');
});
});
精彩评论