I create a website based on Drupal. When I look at the JavaScript and CSS files loaded from Drupal, I see many unwanted files loaded. I want to force Drupal to load only those files added to the .info file and remove everything else. I think I can achieve it by using hook_js_alter()
but I want to know if there is a better solution.
-
1hook_js_alter and hook_css_alter are reliable ways– rémySep 25, 2015 at 5:55
-
@rémy I think so, I can first unset all js(css) data then add theme js(css) files. I ask here maybe another guys has better idea– YuseferiSep 25, 2015 at 5:57
-
1these files are served from drupal and (maybe) your super-theme. there is no other way, except chancing code which you should not touch. with this _alter methods your are totally upgrade save !– rémySep 25, 2015 at 5:59
-
1Removing CSS and Javascript could cause modules not to work properly.– apaderno ♦Sep 25, 2015 at 6:05
-
1@zhilevan In that case I suppose the answer depends on whether your outer MVC template relies on htm.tpl.php or not, and if not if you need to manage your resources via the MVC framework and cycle through the drupal js files via hook_js_alter(). If your view is totally independent of Drupal's theming system then you could just manually add the same files found in the theme's ini file to the MVC framework's resource manager.– J. ReynoldsSep 25, 2015 at 6:50
2 Answers
Drupal only has one sanctioned mechanism for removing specific assets, regardless of the motivation for doing so.
For CSS:
For JS:
To remove all style and scripts except .info
style and script use below codes:
function hook_css_alter(&$css) {
$themes=list_themes();
foreach($css as $key=>$item) {
if (!in_array($key, $themes['yourthemename']->stylesheets['all'])) {
unset($css[$key]);
}
}
}
function hook_js_alter(&$js) {
$themes=list_themes();
foreach($js as $key=>$item) {
if (!in_array($key, $themes['yourthemename']->scripts)) {
unset($js[$key]);
}
}
}
If the theme/module is custom, then obviously you can just remove the offending code manually if that makes more sense.
-
Thanks Dear Clive, I implemented it today and for to be sure I ask here, I had another idea about doing this job, in
html.tpl.php
comment <?print $scripts`($css)?> and add my theme JS (CSS) files in there .– YuseferiSep 25, 2015 at 10:21 -
1@zhilevan If you you do that, I don't believe aggregation or any of the other fancy stuff that can happen with CSS and JS will happen.– mpdonadio ♦Sep 25, 2015 at 15:03
-
If you are getting errors about
missing objects
using @Clive's code, it's because you likely don't have any CSS or JS files defined in your theme's.info
file. Just define at least one JS (or CSS) file to prevent the error:scripts[] = yourthemejsfile.js
– AdrianApr 17, 2018 at 16:00
This code works for removing the CSS from frontend:
libraries-override:
system/base: false
Just use the above in yourtheme.info.yml