So you fired up all of these fancy CSS or JavaScript effects: gradients, shadows, animations, transitions. And things look great on your new hardware. But then you try things on a legacy iPhone or aging laptop. Ugh!
Of course you were smart enough to make your site function fine without them, but how do you disable them? Browser sniffing and separate stylesheets? No no no… don’t be silly. With a little bit of fast-running JavaScript you can easily target that CSS fanciness to only browsers that can handle it.
Here it goes…
// CPU Speed var speedRating = (function() { // Test CPU Speed var init = new Date(), iterations = 25000; while (iterations--) { Math.sqrt(iterations * Math.random()); } var score = new Date - init; // 1-5 star var rating = Math.ceil(((90 - score) / 100) * 5); return (rating < 1) ? 1 : rating; })(); $('body').attr('data-stars', (function() { var stars = '*'; for (var i = 1; i < speedRating; i++) { stars += '*'; } return stars; })() );
Once you’ve done that you can simply use a CSS starts-with attribute selector to target only devices meeting that rating or above on a five-star scale.
body[data-stars^='*'] { background: #eeeeee; } body[data-stars^='**'] { background: #cccccc; } body[data-stars^='***'] { background: #ffdddd; } body[data-stars^='****'] { background: #ffbbbb; } body[data-stars^='*****'] { background: #ff0000; color: #ffffff; }
In theory, if you wanted to make the grading harder for more demanding CPU requirements, just change the 90 to something lower.
Couple this with a little LESS or SASS and it’s easy to target entire blocks of CSS to only the higher end devices!