Skip to content

Instantly share code, notes, and snippets.

@usefulthink
Created March 9, 2013 15:19
Show Gist options
  • Save usefulthink/5124479 to your computer and use it in GitHub Desktop.
Save usefulthink/5124479 to your computer and use it in GitHub Desktop.
Code-Sample for workshops on rendering performance
// DISCLAIMER: errors and worst-practice examples are fully intentional
// our starting-point
(function($, window) {
'use strict';
$(document).on('mousemove', function(ev) {
$('.follow').css('left', ev.pageX - $('.follow').width()/2);
$('.follow').css('top', ev.pageY - $('.follow').height()/2);
});
} (this.jQuery, this));
// refactorings applied:
// - extracted $('.follow') into a variable
// - removed access to .width() and .height() from the hot-code
// - combined multiple .css()-calls into a single one
(function($, window) {
'use strict';
var $follow = $('.follow'),
xOffset = $follow.width()/2,
yOffset = $follow.height()/2;
$(document).on('mousemove', function(ev) {
$follow.css({
left: ev.pageX - xOffset,
top: ev.pageY - yOffset
});
});
} (this.jQuery, this));
// refactorings applied:
// - isolated event-handling- from rendering-code
//
(function($, window) {
'use strict';
var $follow = $('.follow'),
xOffset = $follow.width()/2,
yOffset = $follow.height()/2,
mouseX, mouseY;
$(document).on('mousemove', function(ev) {
mouseX = ev.pageX; mouseY = ev.pageY;
});
function mainloop(t) {
// NOTE: window.requestAnimationFrame() still requires a polyfill:
// http://paulirish.com/2011/requestanimationframe-for-smart-animating/
requestAnimationFrame(mainloop);
$follow.css({
left: mouseX - xOffset,
top: mouseY - yOffset
});
}
mainloop();
} (this.jQuery, this));
// refactorings applied:
// - use of DOM-Elements instead of jQuery
// - added trigger for hw-acceleration
// - added check to prevent uneccessary style-updates
(function($, window) {
'use strict';
var $follow = $('.follow'),
followEl = $follow.get(0),
xOffset = $follow.width()/2,
yOffset = $follow.height()/2,
mouseX, mouseY, lastMouseX, lastMouseY;
$(document).on('mousemove', function(ev) {
mouseX = ev.pageX; mouseY = ev.pageY;
});
// make sure that we get 3d-accelleration to avoid expensive painting for every
// frame (ideally this should be done in the CSS though).
followEl.style.transform = followEl.style.WebkitTransform = 'translateZ(0)';
function mainloop(t) {
requestAnimationFrame(mainloop);
// early escape...
if(mouseX === lastMouseX && mouseY === lastMouseY) { return; }
followEl.style.left = (mouseX-xOffset) + "px";
followEl.style.top = (mouseY-yOffset) + "px";
lastMouseX = mouseX;
lastMouseY = mouseY;
}
mainloop();
} (this.jQuery, this));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment