Skip to content
Snippets Groups Projects
Commit 7231a371 authored by ambient.impact's avatar ambient.impact
Browse files

Issue #3393105: Added JavaScript alter hook to move to <head>.

parent d14779ef
Branches
Tags
No related merge requests found
<?php
declare(strict_types=1);
namespace Drupal\refreshless_turbo\Hooks;
use Drupal\Core\Asset\AttachedAssetsInterface;
use Drupal\Core\Language\LanguageInterface;
use Drupal\hux\Attribute\Alter;
/**
* JavaScript hook implementations.
*/
class Javascript {
#[Alter('js')]
/**
* Move all JavaScript to the <head> as recommended for Hotwire Turbo.
*
* JavaScript found in the <body> will be executed each time that page is
* loaded whereas JavaScript linked in the <head> will only be executed on a
* full page load. Since all Drupal JavaScript should be using behaviours,
* they should all correctly re-attach on every Turbo visit.
*
* @see \hook_js_alter()
*/
public function alter(
array &$javascript,
AttachedAssetsInterface $assets, LanguageInterface $language,
): void {
foreach ($javascript as $filePath => &$settings) {
// Skip items that are already set to the header as they may need to be
// render blocking rather than deferred.
if ($settings['scope'] === 'header') {
continue;
}
$settings['scope'] = 'header';
if (!isset($settings['attributes']['defer'])) {
$settings['attributes']['defer'] = true;
}
}
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment