Drupal 8 for me is one, if not the best CMS that is currently on the market, I think that unlike others it is very organized, it is made in object-oriented PHP which makes it quite good, however it carries something that stops my is a bug that comes from several drupal back "Theme".
What is the problem with the Theme?
If we look at the image, it shows that 77% of the called resources are not being used, when a theme is created it is told which libraries it wants to call for it, in the case of drupal generally we do not have a theme we have at least 2 or 3 counting the administration theme, many times we use a base theme then we create our theme to start customizing, without doing anything to drupal we are loading about 20 or 30 libraries. Now when we start using our custom theme we start creating CSS and JS for the entire site, what is the error we create a style or a javascript that only works for a specific place, however this is propagated throughout the site.
The same thing happens with some modules; they call a library, but they don't call it only where it is required, they propagate it throughout the site.
How to optimize Drupal 8?
Our idea is to separate everything by libraries and only call them when they are needed.
Something very interesting in Drupal is how it handles libraries in modules, a module.libraries.yml file is created in which we can declare x number of libraries.
Example
If we see in the image we have 3 libraries declared, in this file you can call internal and external libraries, in each library you can call 1 or x number of both ccs and js files, something we recommend is compressing the js files from the moment they are He is developing with gulp for example.
Once we have organized the libraries that we are going to use, the next thing is to call them only where they are required, for that we have several ways to do it.
In a block, a controller or a form can be called as shown in the following image.
An attached must be added to the return of the block, controller or form.
Finally, and I think this is the most important thing, we need to remove the loading of the libraries that Drupal loads by default. To do this we do it in the following way.
function hook_page_attachments_alter(array &$attachments) { $current_path = \Drupal::service('path.current')->getPath(); $re = '/([\w\/\-\_\:\.]*)(\/ruta\/ruta)([\w\/\-\_\?\&\.\=\%]*)/i'; if(preg_match($re, $current_path, $matches, PREG_OFFSET_CAPTURE, 0)){ if(\Drupal::currentUser()->isAnonymous()){ unset($attachments['#attached']['library']); } } }
We use hook_page_attachments_alter, we see that we have it conditioned only to a route and only for anonymous users, if we do not want to remove a custom theme we simply place the condition so that it is not removed, we recommend that if the theme is used, it is used exclusively to create styles and js that affect the entire site.