Skip to content

Commit 326952f

Browse files
committed
Optimize performance
Cache jQuery objects instead of creating a new jQuery instance every time.
1 parent df16d2c commit 326952f

File tree

1 file changed

+18
-19
lines changed

1 file changed

+18
-19
lines changed

jquery.rwdImageMaps.js

Lines changed: 18 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -10,52 +10,51 @@
1010
*/
1111
(function($) {
1212
$.fn.rwdImageMaps = function() {
13-
var $img = this,
14-
v = parseFloat($.fn.jquery);
13+
var $img = this;
14+
var v = parseFloat($.fn.jquery);
1515

1616
var rwdImageMap = function() {
1717
$img.each(function() {
1818
if (typeof($(this).attr('usemap')) == 'undefined')
1919
return;
2020

2121
var that = this;
22+
var $that = $(that);
2223
// Since WebKit doesn't know the height until after the image has loaded, perform everything in an onload copy
23-
$('<img />').attr('src', $(that).attr('src')).load(function() {
24+
$('<img />').attr('src', $that.attr('src')).load(function() {
2425
var w, h;
2526
// jQuery < 1.6 incorrectly uses the actual image width/height instead of the attribute's width/height
2627
if (v < 1.6)
27-
w = $(that)[0].getAttribute('width'),
28-
h = $(that)[0].getAttribute('height');
28+
w = that.getAttribute('width'),
29+
h = that.getAttribute('height');
2930
else
30-
w = $(that).attr('width'),
31-
h = $(that).attr('height');
31+
w = $that.attr('width'),
32+
h = $that.attr('height');
3233

33-
var wPercent = $(that).width()/100,
34-
hPercent = $(that).height()/100,
35-
map = $(that).attr('usemap').replace('#', ''),
34+
var wPercent = $that.width()/100,
35+
hPercent = $that.height()/100,
36+
map = $that.attr('usemap').replace('#', ''),
3637
c = 'coords';
3738

3839
$('map[name="' + map + '"]').find('area').each(function() {
39-
if (!$(this).data(c))
40-
$(this).data(c, $(this).attr(c));
40+
var $this = $(this);
41+
if (!$this.data(c))
42+
$this.data(c, $this.attr(c));
4143

42-
var coords = $(this).data(c).split(','),
43-
coordsPercent = new Array(coords.length);
44+
var coords = $this.data(c).split(',');
45+
var coordsPercent = new Array(coords.length);
4446

4547
for (var i = 0; i < coordsPercent.length; ++i) {
4648
if (i % 2 === 0)
4749
coordsPercent[i] = parseInt(((coords[i]/w)*100)*wPercent);
4850
else
4951
coordsPercent[i] = parseInt(((coords[i]/h)*100)*hPercent);
5052
}
51-
$(this).attr(c, coordsPercent.toString());
53+
$this.attr(c, coordsPercent.toString());
5254
});
5355
});
5456
});
5557
};
56-
rwdImageMap();
57-
$(window).resize(function() {
58-
rwdImageMap();
59-
});
58+
$(window).resize(rwdImageMap).trigger('resize');
6059
};
6160
})(jQuery);

0 commit comments

Comments
 (0)