Skip to content

Instantly share code, notes, and snippets.

@Dan0sz
Last active September 21, 2020 07:36
Show Gist options
  • Save Dan0sz/2b694a6b90df662e75b72007ad8098a4 to your computer and use it in GitHub Desktop.
Save Dan0sz/2b694a6b90df662e75b72007ad8098a4 to your computer and use it in GitHub Desktop.
Add (<link rel="">) preconnect, preload and prefetch resource hints to Magento 2's head
<?xml version="1.0" encoding="UTF-8"?>
<!--
/**
* @author : Daan van den Bergh
* @url : https://daan.dev
* @package : Dan0sz/ResourceHints
* @copyright: (c) 2019 Daan van den Bergh
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="layout_generate_blocks_after">
<observer name="dan0sz_resource_hints_framework_view_layout_builder" instance="Dan0sz\ResourceHints\Observer\Framework\View\Layout\Builder" />
</event>
</config>
<?xml version="1.0" encoding="UTF-8"?>
<!--
/**
* @author : Daan van den Bergh
* @url : https://daan.dev
* @package : Dan0sz/ResourceHints
* @copyright: (c) 2019 Daan van den Bergh
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Dan0sz_ResourceHints" setup_version="1.0.0">
<sequence>
<module name="Magento_Catalog" />
</sequence>
</module>
</config>
<?php
/**
* @author : Daan van den Bergh
* @url : https://daan.dev
* @package : Dan0sz/ResourceHints
* @copyright: (c) 2019 Daan van den Bergh
*/
namespace Dan0sz\ResourceHints\Observer\Framework\View\Layout;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\View\Page\Config as PageConfig;
class Builder implements ObserverInterface
{
/** @var PageConfig $pageConfig */
private $pageConfig;
/**
* Builder constructor.
*
* @param PageConfig $pageConfig
*/
public function __construct(
PageConfig $pageConfig
) {
$this->pageConfig = $pageConfig;
}
/**
* @param Observer $observer
*
* @return $this
*/
public function execute(Observer $observer)
{
$resourceHints = [
'google' => [
'resource' => 'https://www.google-analytics.com',
'type' => 'preconnect',
],
'next-page' => [
'resource' => 'https://example.com/next-page',
'type' => 'prefetch'
],
'stylesheet' => [
'resource' => 'styles.css',
'type' => 'preload',
'as' => 'stylesheet'
]
];
foreach ($resourceHints as $resource) {
$this->pageConfig->addRemotePageAsset(
$resource['resource'],
'link_rel',
[
'attributes' => ['rel' => $resource['type'] ]
]
);
}
return $this;
}
}
<?php
/**
* @author : Daan van den Bergh
* @url : https://daan.dev
* @package : Dan0sz/ResourceHints
* @copyright: (c) 2019 Daan van den Bergh
*/
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Dan0sz_ResourceHints',
__DIR__
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment