Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this code optimize minification?

I saw some code here that had these variable declarations:

var equestAnimationFrame = 'equestAnimationFrame',
    requestAnimationFrame = 'r' + equestAnimationFrame,

    ancelAnimationFrame = 'ancelAnimationFrame',
    cancelAnimationFrame = 'c' + ancelAnimationFrame

According to a comment on the page, this is to improve minification, but I couldn't figure out how. Can someone tell me? Thanks.

like image 825
Bobbler Avatar asked Oct 02 '14 08:10

Bobbler


1 Answers

It's not to improve minification proper - the code in question is a requestAnimationFrame polyfill. This means it's going to try different vendor prefixes. So sometimes the code will be "requestAnimationFrame" (lowercase r) and sometimes with a vendor prefix such as msRequestAnimationFrame.

For this reason it is built dynamically, "equestAnimationFrame" is always there but it might be prefixed with an "r" or an "R".

The "improve minification" part is because instead of writing:

var requestAnimationFrame = window.requestAnimationFrame || 
                            window.msRequestAnimationFrame ||
                            window.mozRequestAnimationFrame ||
                            window.webkitRequestAnimationFrame ||
                            window.oRequestAnimationFrame ||

They run a for loop on ["ms","moz","o", "webkit"] and try the prefixes. This saves a few bytes at best.

Here is code I believe is clearer and does the same thing:

var base = "equestAnimationFrame" // the base string
var alternatives = window["r"+base] || // try the basic option first
['moz', 'ms', 'o', 'webkit'].map(function(x){ 
    return x+"R" + base; // all the options
}).filter(function(x){ // check if in window
    return x in window;
})[0];
like image 112
Benjamin Gruenbaum Avatar answered Sep 23 '22 15:09

Benjamin Gruenbaum