-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjavascript_libraries.module
More file actions
84 lines (76 loc) · 2.39 KB
/
javascript_libraries.module
File metadata and controls
84 lines (76 loc) · 2.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
<?php
/**
* @file
* Toggle the inclusion of Drupal system libraries. Upload and reference custom libraries as well.
*/
use Drupal\Core\File;
/**
* Helper function that validates the external url.
* @param $url
* @return bool
*/
function javascript_libraries_valid_external_url($url) {
$parts = parse_url($url);
return $parts && ($parts['scheme'] == 'http' || $parts['scheme'] == 'https') && $parts['host'] && preg_match('@/.+\.(js|txt)$@i', $parts['path']);
}
/**
* Implements hook_page_attachments().
* Used to add the javascript files in the html head section.
* @param array $page
*/
function javascript_libraries_page_attachments(array &$page) {
$external_lib = \Drupal::config('javascript_libraries.settings')
->get('javascript_libraries_custom_libraries');
$externals = array();
$count = 1;
foreach ($external_lib as $key => $lib) {
if ($lib['scope'] == 'header') {
if ($lib['type'] == 'file') {
$lib['uri'] = file_create_url($lib['uri']);
}
$description[$key] = [
'#type' => 'html_tag',
// The HTML tag to add, in this case a tag.
'#tag' => 'script',
'#attributes' => array('src' => $lib['uri']),
];
$page['#attached']['html_head'][] = [$description[$key], 'description'. $count++];
}
}
}
/**
* Implements hook_library_info_build().
* Used in order to declare new library and attach dependency to it.
* @return mixed
*/
function javascript_libraries_library_info_build() {
$external_lib = \Drupal::config('javascript_libraries.settings')
->get('javascript_libraries_custom_libraries');
$externals = array();
foreach ($external_lib as $key => $lib) {
if ($lib['scope'] == 'footer') {
if ($lib['type'] == 'file') {
$lib['uri'] = file_create_url($lib['uri']);
}
$externals[$lib['uri']] = array(
'type' => 'external',
'minified' => 'true'
);
}
}
$core_lib = \Drupal::config('javascript_libraries.settings')
->get('javascript_libraries_core_libraries');
foreach ($core_lib as $key => $lib) {
$dependencies[] = $lib;
}
$libraries['external']['dependencies'] = $dependencies;
$libraries['external']['js'] = $externals;
return $libraries;
}
/**
* Implements hook_preprocess_page.
* @param $variables
*/
function javascript_libraries_preprocess_page(&$variables) {
$variables['#attached']['library'][] = 'javascript_libraries/external';
}