Reputation: 562
I have a website with certain animations, CSS, animated gifs and "JS animations". On some mobile devices the animations are slow, so I want to detect that and turn the CSS animation off and use a static image for the gif animations instead.
The mobile devices browser do support CSS animations, but they're slow when it executes.
How can I measure the actual browser performance with a Javascript function so I can decide whether turn animations on or off? Any Javascript library maybe?
Upvotes: 0
Views: 220
Reputation: 13
performance.now() is more accurate than using Date:
var t0 = performance.now();
your_function();
var t1 = performance.now();
console.log("Call to your_function took " + (t1 - t0) + " milliseconds.");
And read the output in your console.
Upvotes: 1
Reputation: 32511
The only way to test the performance of a function is to run it. You could setup some kind of initial tests like the following:
var startTime = new Date();
possiblySlowFunction();
if (new Date() - startTime > maxAcceptableTime) {
disableCSSAnimations();
}
The idea being, you give it a test run to determine how well it performs. In the case that it takes too long, do something to prevent using it again.
Edit: I'm making some mild assumptions with this answer. If this is a function that's been written by you, you'll first need to figure out what part of the function takes the longest. Then you can isolate that section into a test like what you see above and find a good number for determining if the function performs well enough.
Say, for example, you have an animation which requires you to alter a canvas on a per-pixel basis. You could setup a test which runs on a canvas 10x smaller than your real canvas and run the same algorithm on it. Now you have a benchmark for how long it takes on a smaller canvas so take that time and multiply it by 10. Is that an acceptable time for that animation? If not, disable the per-pixel canvas animations. This idea can be used for any kind of function, animation or otherwise.
Upvotes: 0