Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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 } ?>
@aonurdemir

This comment has been minimized.

Copy link

commented Mar 16, 2017

Is there a way to implement this by gulp?

@debiprasad

This comment has been minimized.

Copy link

commented Jun 20, 2017

It does not work, when I tried to do it for multiple pages. In that case, it only works for the last entry.

@debiprasad

This comment has been minimized.

Copy link

commented Sep 17, 2017

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
You can’t perform that action at this time.