Skip to content

Instantly share code, notes, and snippets.

@pocketjoso
Last active September 17, 2017 13:55
Show Gist options
  • Save pocketjoso/58cb89ad9e69e4da297e to your computer and use it in GitHub Desktop.
Save pocketjoso/58cb89ad9e69e4da297e to your computer and use it in GitHub Desktop.
Critical css for PHP sites using grunt-penthouse (could use Penthouse's node module to exact same effect)
// gruntfile.js
-----------------------
// make sure you're actually running a php server locally first!
// Output a critical css file in same folder with same name as php file, just add '.css' extensions
// This makes it super easy to find from php.
penthouse: {
work : {
css : 'pathToMyFullCss.css',
url : 'localhost:8000/work/index.php',
outfile : 'work/index.php.css',
width : 1300,
height : 900
},
... other pages
}
$pagefile = $_SERVER['DOCUMENT_ROOT'] . htmlspecialchars($_SERVER['PHP_SELF']);
$critcssfile = $pagefile . ".css";
if (file_exists($critcssfile)) { ?>
<!-- inline critical css -->
<style><?php include($critcssfile);?></style>
<!-- use loadCSS to load full CSS async, from: https://github.com/filamentgroup/loadCSS -->
<script>
function loadCSS(n,e,o,d){"use strict";var t=window.document.createElement("link"),i=e||window.document.getElementsByTagName("script")[0],l=window.document.styleSheets;return t.rel="stylesheet",t.href=n,t.media="only x",d&&(t.onload=d),i.parentNode.insertBefore(t,i),t.onloadcssdefined=function(e){for(var o,d=0;d<l.length;d++)l[d].href&&l[d].href.indexOf(n)>-1&&(o=!0);o?e():setTimeout(function(){t.onloadcssdefined(e)})},t.onloadcssdefined(function(){t.media=o||"all"}),t}
loadCss('pathToMyFullCss.css');
</script>
<!-- provide a no JS fallback to get the full css -->
<noscript><link rel='stylesheet' href='pathToMyFulLCss.css' /></noscript>
} else { ?>
<!-- no critical css for page - just load full css in render blocking way.. -->
<link rel='stylesheet' href='pathToMyFullCss.css' />
<?php } ?>
@debiprasad
Copy link

I figured out that the term 'work' could be anything. So, you need to keep it unique for all pages and can do multiple pages at once.

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