Created
May 9, 2012 07:06
-
-
Save swissmanu/2642579 to your computer and use it in GitHub Desktop.
simplyfied requestAnimationFrame
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* An even more common approach to look for vendor specific implementations in | |
* the browsers javascript object model. | |
* lookUpImplementation(vendors,subject,functionName,replacement) is reusable | |
* for other tasks too :-) | |
*/ | |
var vendors = ['webkit','moz','o','ms']; | |
window.requestAnimationFrame = lookUpImplementation( | |
vendors, window, 'requestAnimationFrame' | |
,function(step) { | |
return setInterval(step, 1000/60); | |
} | |
); | |
window.cancelAnimationFrame = lookUpImplementation( | |
vendors, window, 'cancelAnimationFrame' | |
,function(id) { | |
clearInterval(id); | |
} | |
); | |
/** PrivateFunction: lookUpImplementation(vendors, subject, functionName, replacement) | |
* Searches for a function with the name "functionName" inside of | |
* "subject". | |
* If the function was not found, the vendor prefixes from the array | |
* "vendors" are prepended to "functionName" to check, if a function | |
* from the regarding vendor exists. | |
* If a "native" or a "vendor" implementation was found, it gets | |
* returned. If not, "replacement" gets returned instead (if given) | |
* | |
* "functionName" will be reformatted automatically to match | |
* camelcase notation when prepending vendor prefixes. Means: | |
* "toLookup" becomes automatically "webkitToLookup". | |
* | |
* Parameters: | |
* (Array) vendors - vendor prefixes like "webkit" or "moz" | |
* (mixed) subject - an object too search for implementations | |
* (String) functionName - name of the implementation | |
* (Function) replacement - this gets returned if a native nor a | |
* vendor specific implementation was found. | |
* | |
* Returns: | |
* (Function|undefined) | |
*/ | |
function lookUpImplementation(vendors, subject, functionName, replacement) { | |
var implementation; | |
if(subject) { | |
if(subject[functionName]) { | |
implementation = subject[functionName]; | |
} else { | |
var camelnotation = functionName.substr(0,1).toUpperCase() | |
+ functionName.substr(1); | |
for(var i = 0, l = vendors.length; i < l; i++) { | |
var vendorFn = vendors[i]+camelnotation; | |
if(subject[vendorFn]) { | |
implementation = subject[vendorFn]; | |
break; | |
} | |
} | |
} | |
} | |
if(!implementation && replacement) { | |
implementation = replacement; | |
} | |
return implementation; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment