Create a gist now

Instantly share code, notes, and snippets.

@rwaldron /raf.js
Last active Jun 18, 2016

requestAnimationFrame, browser prefix detection
var rAF = "equestAnimationFrame";
window["r"+rAF] = window["r"+rAF] ||
window["webkitR"+rAF] ||
window["mozR"+rAF] ||
window["msR"+rAF] ||
window["oR"+rAF];
// A list
[ "r", "webkitR", "mozR", "msR", "oR", "" ].join( rAF + "," ).split( "," )
// Best one yet:
[ "r", "webkitR", "mozR", "msR", "oR" ].reduce(function( p, v ) {
return window[ v + p ] || p;
}, "equestAnimationFrame");
// Just the prefix
var prefix = [ "r", "webkitR", "mozR", "msR", "oR" ].reduce(function( p, v ) {
return (window[ v + p ] && v.slice(0, -1)) || p;
}, "equestAnimationFrame");
// Polyfills...
// requestAnimationFrame (from requestAnimationFrame)
// cancelAnimationFrame (from cancelAnimationFrame or cancelRequestAnimationFrame)
(function(window) {
var time, can, raf, pfx;
time = 0;
can = "Cancel";
raf = "RequestAnimationFrame";
pfx = ["r", "webkitR", "mozR", "msR", "oR"].reduce(function(p, v) {
return (window[v + p] && v.slice(0, -1)) || p;
}, raf.slice(1));
window.requestAnimationFrame = window[pfx + raf] || function(callback, element) {
var now, callAt;
now = +new Date();
callAt = Math.max(0, 16 - (now - time));
time = now + callAt;
return setTimeout(function() {
callback(time);
}, callAt);
};
window.cancelAnimationFrame = window[pfx + can + raf] ||
window[pfx + raf.replace(raf.slice(0, 7), can)] || function(id) {
clearTimeout(id);
};
}(this));
["r","webkitR","mozR","msR","oR"].reduce(function(p, v) { return window[v + p] || p; }, "equestAnimationFrame");
// Alternate approach ideas
var suffix = "equestAnimationFrame",
rAF = [ "r", "webkitR", "mozR", "msR", "oR" ].filter(function( val ) {
return val + suffix in window;
})[ 0 ] + suffix;
/*
var suffix="equestAnimationFrame",rAF=["r","webkitR","mozR","msR","oR"].filter(function(a){return a+suffix in window})[0]+suffix;
Original Size: 179 bytes (164 bytes gzipped)
Compiled Size: 129 bytes (131 bytes gzipped)
Saved 27.93% off the original size (20.12% off the gzipped size)
*/
var prefix = function(window) {
var raf = "RequestAnimationFrame",
idx;
for (var prop in window) {
idx = prop.indexOf(raf);
if (idx > -1) {
return prop.slice(0, idx);
}
}
return null;
}(this);
/*
var prefix=function(c){var a,b;for(b in c)if(a=b.indexOf("equestAnimationFrame"),a>-1)return b.slice(0,a-1);return null}(this);
Original Size: 232 bytes (184 bytes gzipped)
Compiled Size: 127 bytes (130 bytes gzipped)
Saved 45.26% off the original size (29.35% off the gzipped size)
*/
console.log(
prefix
);
@arxpoetica

"Best " + ["s","webkitS","mozS","msS","oS"].reduce(function(p, v) { return window[v + p] || p; }, "him yet");

@JinJunho

["r","webkitR","mozR","msR","oR"].reduce(function(p, v) { return window[v + p] || p; }, "equestAnimationFrame");

This trick is awesome.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment