Sometimes we add Jquery file by libraries.yml but if we want to add JS file by `.theme` file in drupal 8 so we will add <script> code in `hook_page_attachments_alter`.
There we will create a variable and put the script code and then add in $page['#attached']['html_head'][].
We will add #tag is script and pass the script code variable using this code of line..
\Drupal\Core\Render\Markup::create($javascript_header)
here $javascript_header is our script code variable.
Example:
<?php
function hook_page_attachments_alter(array &$page) {
$javascript_header = 'var hmt = hmt || [];
(function()
{
var hm = document.createElement("script");
hm.src = "https://hm.baidu.com/hm.js?1236547890";
var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(hm, s);
}
)();';
$page['#attached']['html_head'][] = [
[
'#tag' => 'script',
'#value' => \Drupal\Core\Render\Markup::create($javascript_header),
'#weight' => -1,
],
'key'
];
}
?>
So this is simple way to add JS file in header of project of Drupal 8.
Note: If have any suggestions or issue regarding 'How to add JS file using theme file in Drupal 8 ?' then you can ask by comments.
There we will create a variable and put the script code and then add in $page['#attached']['html_head'][].
We will add #tag is script and pass the script code variable using this code of line..
\Drupal\Core\Render\Markup::create($javascript_header)
here $javascript_header is our script code variable.
Example:
<?php
function hook_page_attachments_alter(array &$page) {
$javascript_header = 'var hmt = hmt || [];
(function()
{
var hm = document.createElement("script");
hm.src = "https://hm.baidu.com/hm.js?1236547890";
var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(hm, s);
}
)();';
$page['#attached']['html_head'][] = [
[
'#tag' => 'script',
'#value' => \Drupal\Core\Render\Markup::create($javascript_header),
'#weight' => -1,
],
'key'
];
}
?>
So this is simple way to add JS file in header of project of Drupal 8.
Note: If have any suggestions or issue regarding 'How to add JS file using theme file in Drupal 8 ?' then you can ask by comments.