我编写了一个能够提取 HTML 文档中使用的 CSS 内容的代码,这应该被缓存,作为物化的库需要 15 秒来寻找 t2.micro AWS 实例中 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);