Skip to content

Instantly share code, notes, and snippets.

@debiprasad
Forked from pocketjoso/gruntfile.js
Last active June 20, 2017 11:08
Show Gist options
  • Save debiprasad/5c235b207ce88031720f4c192dadf230 to your computer and use it in GitHub Desktop.
Save debiprasad/5c235b207ce88031720f4c192dadf230 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: {
extract : {
css : 'pathToMyFullCss.css',
url : 'localhost:8000/work/index.php',
outfile : 'work/index.php.css',
width : 1300,
height : 900
},
... other pages
}
<?php
$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>
<?php } else { ?>
<!-- no critical css for page - just load full css in render blocking way.. -->
<link rel='stylesheet' href='pathToMyFullCss.css' />
<?php } ?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment