由于CSS文件的原因,我在桌面和移动版的谷歌PageSpeed洞察中失败了一个唯一点,“错误”写道:
消除渲染阻塞JavaScript和CSS在上面折叠的内容,您的网页有1个阻塞CSS资源.这会导致呈现页面的延迟。如果不等待加载以下资源,页面上的任何上述折叠内容都无法呈现。尝试推迟或异步加载阻塞资源,或直接在HTML中内联这些资源的关键部分。
Google开发人员推荐说
如果外部CSS资源较小,则可以将这些资源直接插入HTML文档,这称为内联。以这种方式内联小CSS允许浏览器继续呈现页面。请记住,如果CSS文件是大的,完全内联CSS可能会导致PageSpeed洞察警告,上面的折叠部分您的页面太大,通过优先可见的内容。在大型CSS文件的情况下,您将需要识别并内联呈现上述折叠内容所需的CSS,并将其余样式的加载推迟到上述折叠内容之后。
但是,我使用的是物化CSS / CSS/JS库。这样的库包含一个大的最小化css文件,它适用于所有的东西。我无法提取在上述内容中使用的部分,甚至无法保持其可维护性/可更新性。
一个选项是在加载窗口事件之后加载css,但在这种情况下,应用程序在加载css之前加载得很难看。
是否有一种方法可以使用CSS、Foundation或类似的类库来完成Google建议?
发布于 2015-05-25 17:45:14
我编写了一段代码,可以提取HTML文档中使用的CSS内容,这应该被缓存,物化库需要15秒才能在t2.microAWS实例中寻找200行HTML中的每个选择器。
use PHPHtmlParser\Dom;
ob_start();
?><!doctype html>
<html>
<head>
.....
</body>
</html><?PHP
$html = ob_get_contents();
ob_end_clean();
$md5 = md5($html);
if($memcached->append($md5, NULL)==TRUE){
echo $memcached->get($md5);
}else{
//add to HTML in style labels the CSS Used and minimized the result
$dom = new Dom;
$dom->load($html);
$style = '';
foreach($css_files as $css_file){
$md5CSS = md5_file($css_file);
if($memcached->append($md5CSS, NULL)==TRUE){
$cssParsed = $memcached ->get($md5CSS);
}else{
$cssContent = file_get_contents($css_file);
$oSettings = Sabberworm\CSS\Settings::create()->withMultibyteSupport(false)/*->beStrict()*/;
$oCssParser = new Sabberworm\CSS\Parser($cssContent, $oSettings);
$cssParsed = $oCssParser->parse();
$memcached->set($md5CSS, $cssParsed);
}
foreach ($cssParsed->getContents() as $oItem) {
if ($oItem instanceof Sabberworm\CSS\CSSList\KeyFrame)
continue;
if ($oItem instanceof Sabberworm\CSS\RuleSet\AtRuleSet)
continue;
if($oItem instanceof Sabberworm\CSS\RuleSet\DeclarationBlock){
$oBlock = $oItem;
$selectors = array();
foreach($oBlock->getSelectors() as $oSelector)
$selectors[] = $oSelector->getSelector();
if(count($dom->find(implode(",",$selectors))) > 0)
$style .= $oBlock->render(Sabberworm\CSS\OutputFormat::createCompact());
}
if ($oItem instanceof Sabberworm\CSS\CSSList\AtRuleBlockList) {
foreach($oItem->getContents() as $oBlock) {
$selectors = array();
foreach($oBlock->getSelectors() as $oSelector)
$selectors[] = $oSelector->getSelector();
if(count($dom->find(implode(",",$selectors))) > 0){
$style .= $oItem->render(Sabberworm\CSS\OutputFormat::createCompact());
break;
}
}
}
}
}
$styleLabel = '<style type="text/css">'.$style.'</style>';
$html = str_replace("</head>", $styleLabel."\n</head>",$html);https://stackoverflow.com/questions/30401232
复制相似问题