protected function CssCollectionRenderer::makeAssetsAsync in Critical CSS 8
Get critical CSS element.
It's an array that should be placed into $css_assets array from render() method.
Parameters
array $css_assets: Array of CSS assets.
Return value
array Array with two items (start and end string) ready to be used as debug info.
1 call to CssCollectionRenderer::makeAssetsAsync()
- CssCollectionRenderer::render in src/
Asset/ CssCollectionRenderer.php - Renders an asset collection.
File
- src/
Asset/ CssCollectionRenderer.php, line 145
Class
- CssCollectionRenderer
- Decorates the CSS collection renderer service, adds Critical CSS.
Namespace
Drupal\critical_css\AssetCode
protected function makeAssetsAsync(array $css_assets) {
$asyncAssets = [];
foreach ($css_assets as $asset) {
// Skip files with print media.
if ($asset['#attributes']['media'] === 'print') {
$asyncAssets[] = $asset;
}
else {
if ($this->configFactory
->get('critical_css.settings')
->get('preload_non_critical_css')) {
// Add a preload link so non-critical CSS is loaded with the highest
// priority.
$preloadAsset = $asset;
$preloadAsset['#attributes']['rel'] = 'preload';
$preloadAsset['#attributes']['as'] = 'style';
unset($preloadAsset['#attributes']['media']);
$asyncAssets[] = $preloadAsset;
}
// Add a stylesheet link with print media and an "onload" event.
// @see https://www.filamentgroup.com/lab/load-css-simpler/
// TODO Find a better way to set the onload attribute:
// Due to Drupal escaping quotes inside an attribute, we need to set a
// dummy "data-onload-media" attribute, only needed for the onload
// attribute.
// "this.media='all'" gets escaped into
// "this.media='all'".
$onLoadAsset = $asset;
$onLoadAsset['#attributes']['media'] = 'print';
$onLoadAsset['#attributes']['data-onload-media'] = 'all';
$onLoadAsset['#attributes']['onload'] = 'this.onload=null;this.media=this.dataset.onloadMedia';
$asyncAssets[] = $onLoadAsset;
// Add fallback element for non-JS browsers.
$noScriptAsset = $asset;
$noScriptAsset['#noscript'] = TRUE;
$asyncAssets[] = $noScriptAsset;
}
}
return $asyncAssets;
}