Skip to content

Commit

Permalink
Merge pull request #114 from tbela99/automate_critical_css_1
Browse files Browse the repository at this point in the history
improve ligthouse score on mobile and desktop #84
  • Loading branch information
tbela99 authored Oct 12, 2020
2 parents ae6d55c + 0180161 commit d108aa3
Show file tree
Hide file tree
Showing 23 changed files with 215 additions and 2,472 deletions.
Binary file modified Capture.PNG
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
8 changes: 8 additions & 0 deletions helper.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,16 @@ class GZipHelper
const regexAttr = '~([\r\n\t ])?([a-zA-Z0-9:-]+)((=(["\'])(.*?)\5)|([\r\n\t ]|$))?~m'; #s
const regexUrl = '#url\(([^)]+)\)#';

/**
* @var string regex
* @since version
*/
static $regReduce = '';

/**
* @var string route prefix
* @since version
*/
static $route = '';

static $options = [];
Expand Down
218 changes: 119 additions & 99 deletions helpers/CSS.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ class CSSHelper
*
* @return string
*
* @throws Parser\SyntaxError
* @throws \Exception
* @since version
*/
public function processHTML($html, array $options = [])
Expand All @@ -45,7 +47,7 @@ public function processHTML($html, array $options = [])
$fetch_remote = !empty($options['fetchcss']);

$links = [];
$root = $options['uri_root'];
// $root = $options['uri_root'];
$ignore = !empty($options['cssignore']) ? $options['cssignore'] : [];
$remove = !empty($options['cssremove']) ? $options['cssremove'] : [];

Expand All @@ -60,9 +62,9 @@ public function processHTML($html, array $options = [])
$cssRenderer = new Renderer($css_options);
$headStyle = new Stylesheet();

$parseUrls = function ($html) use($path, $root) {
$parseUrls = function ($html) use($path) {

return preg_replace_callback('~url\(([^)]+)\)~', function ($matches) use($path, $root) {
return preg_replace_callback('~url\(([^)]+)\)~', function ($matches) use($path) {

$url = preg_replace('~^(["\'])?([^\1]+)\1~', '$2', trim($matches[1]));

Expand All @@ -88,13 +90,13 @@ public function processHTML($html, array $options = [])

if (is_file($localName)) {

return 'url('.$root.$localName.')';
return 'url('.GZipHelper::url($localName).')';
}
}

if (substr($url, 0, 1) != '/') {

return 'url('.$root.$url.')';
return 'url('.GZipHelper::url($url).')';
}

return $matches[0];
Expand Down Expand Up @@ -232,7 +234,7 @@ public function processHTML($html, array $options = [])
$cssParser->append($attr['href']);
}

file_put_contents($file, $parseUrls($cssRenderer->render($cssParser->parse())));
file_put_contents($file, $parseUrls($cssRenderer->render($this->parseBackgroundImages($cssParser->parse()))));
}

$links[$position]['links'] = [
Expand Down Expand Up @@ -264,7 +266,7 @@ public function processHTML($html, array $options = [])
if (!is_file($file)) {

$cssParser->load($attr['href']);
file_put_contents($file, $parseUrls($cssRenderer->render($cssParser->parse())));
file_put_contents($file, $parseUrls($cssRenderer->render($this->parseBackgroundImages($cssParser->parse(), $options))));
}
}

Expand Down Expand Up @@ -383,103 +385,19 @@ public function processHTML($html, array $options = [])
}
}

if ($parseCssResize) {
// if ($parseCssResize) {

$img_path = $options['img_path'];
$method = empty($options['imagesresizestrategy']) ? 'CROP_FACE' : $options['imagesresizestrategy'];
$const = constant('\Image\Image::'.$method);
$short_name = strtolower(str_replace('CROP_', '', $method));
// $img_path = $options['img_path'];
// $method = empty($options['imagesresizestrategy']) ? 'CROP_FACE' : $options['imagesresizestrategy'];
// $const = constant('\Image\Image::'.$method);
// $short_name = strtolower(str_replace('CROP_', '', $method));

/**
* @var Element $property
*/
// all fonts with an src attribute
foreach ($headStyle->query('[@name="background"]|[@name="background-image"]') as $property) {

$images = [];
$property->getValue()->map(function ($value) use(&$images) {

/**
* @var Value $value
*/

if ($value->type == 'css-url') {

$name = GZipHelper::getName(preg_replace('#(^["\'])([^\1]+)\1#', '$2', trim($value->arguments->{0})));

if (GZipHelper::isFile($name)) {

if (in_array(strtolower(pathinfo($name, PATHINFO_EXTENSION)), ['jpg', 'png', 'webp'])) {

$images[] = [

'file' => $name,
'size' => getimagesize($name)
];
}

return Value::getInstance((object) [
'name' => 'url',
'type' => 'css-url',
'arguments' => new Value\Set([
Value::getInstance((object) [
'type' => 'css-string',
'value' => GZipHelper::url($name)
])
])
]);
}
}

return $value;
});

// ignore multiple backgrounds
if (count($images) == 1) {

foreach ($images as $settings) {

$img = null;
$hash = GZipHelper::shorten(crc32($settings['file']));

foreach ($options['css_sizes'] as $size) {

if ($size < $settings['size'][0]) {

$crop = $img_path.$hash.'-'. $short_name.'-'.$size.'-'.basename($settings['file']);

if (!is_file($crop)) {

if (is_null($img)) {

$img = new Image($settings['file']);

if ($img->getWidth() > 1200) {

$img->setSize(1200);
}
}

$img->resizeAndCrop($size, null, $const)->save($crop);
}

if (is_file($crop)) {

$property = $property->copy();
$property->setName('background-image');
$property->setValue('url('.GZipHelper::url($crop).')');

$headStyle->addAtRule('media', '(max-width:'.$size.'px)')->append($property->getRoot());
}
}
}
}
}
}
}
// $this->parseBackgroundImages($headStyle, $options);
// }

$headStyle->deduplicate();
file_put_contents($css_hash, $cssRenderer->render($headStyle));
file_put_contents($css_hash, $parseUrls($cssRenderer->render($headStyle)));
}

if (is_file($css_hash)) {
Expand Down Expand Up @@ -621,4 +539,106 @@ public function processHTML($html, array $options = [])

return $html;
}

public function parseBackgroundImages(Element $headStyle, array $options = []) {

if (empty($options['imagecssresize']) || empty($options['css_sizes'])) {

return $headStyle;
}

$img_path = $options['img_path'];
$method = empty($options['imagesresizestrategy']) ? 'CROP_FACE' : $options['imagesresizestrategy'];
$const = constant('\Image\Image::'.$method);
$short_name = strtolower(str_replace('CROP_', '', $method));

$stylesheet = new Stylesheet();

foreach ($headStyle->query('[@name="background"]|[@name="background-image"]') as $property) {

$images = [];
$property->getValue()->map(function ($value) use(&$images) {

/**
* @var Value $value
*/

if ($value->type == 'css-url') {

$name = GZipHelper::getName(preg_replace('#(^["\'])([^\1]+)\1#', '$2', trim($value->arguments->{0})));

if (GZipHelper::isFile($name)) {

if (in_array(strtolower(pathinfo($name, PATHINFO_EXTENSION)), ['jpg', 'png', 'webp'])) {

$images[] = [

'file' => $name,
'size' => getimagesize($name)
];
}

return Value::getInstance((object) [
'name' => 'url',
'type' => 'css-url',
'arguments' => new Value\Set([
Value::getInstance((object) [
'type' => 'css-string',
'value' => GZipHelper::url($name)
])
])
]);
}
}

return $value;
});

// ignore multiple backgrounds
if (count($images) == 1) {

foreach ($images as $settings) {

$img = null;
$hash = GZipHelper::shorten(crc32($settings['file']));

foreach ($options['css_sizes'] as $size) {

if ($size < $settings['size'][0]) {

$crop = $img_path.$hash.'-'. $short_name.'-'.$size.'-'.basename($settings['file']);

if (!is_file($crop)) {

if (is_null($img)) {

$img = new Image($settings['file']);

if ($img->getWidth() > 1200) {

$img->setSize(1200);
}
}

$img->resizeAndCrop($size, null, $const)->save($crop);
}

if (is_file($crop)) {

$property = $property->copy();
$property->setName('background-image');
$property->setValue('url('.GZipHelper::url($crop).')');

$stylesheet->addAtRule('media', '(max-width:'.$size.'px)')->append($property->getRoot());
}
}
}
}
}
}

$headStyle->insert($stylesheet, 0);

return $headStyle;
}
}
2 changes: 1 addition & 1 deletion helpers/HTML.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ public function preProcessHTML($html, array $options = []) {

if(!empty($script)) {

$html = str_replace('</head>', $css.'<script data-position="head">'.$script.'</script></head>', $html);
$html = str_replace('</head>', $css.'<script data-ignore="true">'.$script.'</script></head>', $html);
}

$script = '';
Expand Down
4 changes: 2 additions & 2 deletions imagesloader.es6
Original file line number Diff line number Diff line change
Expand Up @@ -147,8 +147,8 @@ LIB.ready(function (undef) {
if (container) {
container.parentElement.removeChild(container);
}
}, 10);
}, 10);
}, 5);
}, 5);
}

if (
Expand Down
4 changes: 2 additions & 2 deletions imagesloader.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,8 @@ LIB.ready((function(e) {
// container.classList.add("image-placeholder-complete");
e && e.parentElement.insertBefore(t, e), setTimeout((function() {
t.classList.remove("image-placeholder-complete"), e && e.parentElement.removeChild(e);
}), 10);
}), 10);
}), 5);
}), 5);
}
if (
// intersection-observer.min.js
Expand Down
2 changes: 1 addition & 1 deletion imagesloader.min.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

22 changes: 14 additions & 8 deletions js/dist/lib.images.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,18 @@ var LIB = (function (exports) {
const queue = [];
let fired = document.readyState != 'loading';

function domReady() {

document.removeEventListener('DOMContentLoaded', domReady);
document.removeEventListener('readystatechange', readystatechange);
fired = true;

while (queue.length > 0) {

requestAnimationFrame(queue.shift());
}
}

function readystatechange() {

switch (document.readyState) {
Expand All @@ -16,18 +28,12 @@ var LIB = (function (exports) {
case 'interactive':
default:

fired = true;

while (queue.length > 0) {

requestAnimationFrame(queue.shift());
}

document.removeEventListener('readystatechange', readystatechange);
domReady();
break;
}
}

document.addEventListener('DOMContentLoaded', domReady);
document.addEventListener('readystatechange', readystatechange);

function ready(cb) {
Expand Down
Loading

0 comments on commit d108aa3

Please sign in to comment.