Skip to content

Instantly share code, notes, and snippets.

@zakirt
Last active September 28, 2015 00:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zakirt/eb9cd215170997e8ad55 to your computer and use it in GitHub Desktop.
Save zakirt/eb9cd215170997e8ad55 to your computer and use it in GitHub Desktop.
Optimize CSS performance with requestAnimationFrame bug fixed.
<!DOCTYPE html>
<html>
<head>
<style>
/*
Inline above the fold CSS
*/
</style>
<noscript><link rel="stylesheet" href="/css/below-the-fold.min.css"></noscript>
</head>
<body>
<!-- HTML Content -->
<script>
/*
Load below the fold CSS
*/
// Use setTimeout to make this JS code asynchronous
setTimeout(function() {
var cb = function() {
var l = document.createElement('link');
var h = document.getElementsByTagName('head')[0];
l.rel = 'stylesheet';
l.href = '/css/below-the-fold.min.css';
h.parentNode.insertBefore(l, h);
};
var vendors = ['ms', 'moz', 'webkit', 'o'];
var raf = window.requestAnimationFrame;
for (var i = 0, len = vendors.length; i < len && !raf; i += 1) {
raf = window[vendors[i] + 'RequestAnimationFrame'];
}
if ( raf ) {
raf(cb);
} else {
window.addEventListener('load', cb);
}
});
</script>
</body>
</html>
@zakirt
Copy link
Author

zakirt commented Sep 18, 2015

This fork from https://gist.github.com/sergejmueller/f25b0df24775aea20add uses setTimeout function to make entire CSS loading JS code asynchronous and thus prevent lower score from Google Page Insights score when trying to use requestAnimationFrame variations off the window object.

See links below for more details on the issue:
https://groups.google.com/forum/#!topic/pagespeed-insights-discuss/hyFjqKBDakM
http://stackoverflow.com/questions/32574729/pagespeed-optimize-css-delivery-script-bug-with-window-object

@mt3o
Copy link

mt3o commented Sep 21, 2015

Can you use my trick with async css from here: https://gist.github.com/mt3o/4767557b64cdd8c6d6d1 to load nonctritical css?

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