Last active
September 17, 2017 13:55
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$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 } ?> |
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
It does not work, when I tried to do it for multiple pages. In that case, it only works for the last entry.