Skip to content
Menu
Open World News Open World News
  • Privacy Policy
Open World News Open World News

Specbee: Using Drupal 10’s Asset Library to Streamline Asset Handling

Posted on May 7, 2024 by Michael G

Author:
Source

Drupal 7 lacked a streamlined mechanism for handling assets, which necessitated the development of more efficient solutions like the Asset Library introduced in Drupal 8 and the latest versions. Asset library solves the problem of loading JS and CSS files on every page. However, unless specified, Drupal does not load these assets as it can affect front-end performance.
Let’s learn more about asset libraries in Drupal 10 and how to work with them.

What is an Asset Library in Drupal
An Asset library in Drupal is nothing but a YAML data structured inside a THEMENAME.libraries.yml file and they contain only CSS and JS files. They are the bundles of CSS and JavaScript files that present inside a module or theme and perform together for style and functionality.

The Asset Library in Drupal provides a centralized and organized repository for managing various types of digital assets.
Assets Library boasts various features designed to enhance usability, scalability, and flexibility.
Asset Library in Drupal is designed to support responsive web design, ensuring that assets are displayed consistently on various devices.
Drupal places a strong emphasis on accessibility, and the Asset Library follows these standards to ensure a positive user experience for all.
Drupal’s Asset Library includes version control features, allowing users to manage and track changes to assets over time.
Performance Optimization

Define an Asset Library
Let’s declare a new Asset library named custom-slider.
custom-slider:
  version: 1.0
  CSS:
    theme:
      css/custom-slider-theme.css: {}
  js:
    js/custom-slider.js: {}Some of the attributes used include:

Minified: If the file is already minified, set this to True to avoid minifying it again, else default value is False.
Preprocess: Default value is True, set to False to exclude a file from Aggregation.
Type (Javascript Only):        ◦ The default value is a file, if you leave it blank.       ◦ For external files, use type as external like:

//cdn.com/js/example.js: {type: external}Assets Loading Order

By default, all JS files are loaded in the order in which files are listed.
By default, JS files are loaded in the footer.
Set header: true for a library to get loaded in the header.
For example:

jquery.ui:
  header: true
  js:
    assets/vendor/jquery.ui/ui/core-min.js: {}SMACSS Categorization

Drupal follows a SMACSS-style categorization and all CSS files are loaded first based on their category and then by the order.
SMACSS categorization is used to set the weight of CSS files, this will not work for JS files.
To set CSS weights there are 5 different levels:       ◦ base – This rule consists of styling HTML elements only. CSS_BASE = -200       ◦ layout – Macro management of page or arrangements of elements on the page, including any grid system. CSS_LAYOUT = -100       ◦ component – Components are reusable and discrete UI elements. CSS_COMPONENT = 0       ◦ state – Styles that deal mostly with client-side changes such as hovering links, opening modal dialog, etc. CSS_STATE = 100       ◦ theme – This is purely visual styling such as box-shadow, backgrounds, borders, colors, etc. CSS_THEME = 200

Attach an Asset Library
1. Globally: 

We can attach the asset library globally via the THEMENAME.info.yml file, but this approach would work only for a Theme.
For any modules you should use hook_page_attachments_alter() or similar.
For example:

name: ‘My Custom Theme’
type: theme
description: ‘A custom Drupal 9 theme for demonstration purposes.’
package: Custom
core_version_requirement: ^8 || ^9 || ^10
base theme: false

libraries:
  – THEMENAME/global-styling
  – THEMENAME/global-scripts2. Conditionally, via a preprocess function using #attached: 
If you need to restrict the library to a particular page or element, then this is the best way to add libraries.
For example:Taking a case where we need to attach a library to our page, then we can use hook_page_attachments_alter():
/**
* Implements hook_page_attachments_alter().
*/
function custom_module_page_attachments_alter(array &$attachments) {
  // Adding stylesheet to the page.
  $attachments[‘#attached’][‘library’][] = ‘custom_module/custom-styles’;
 
  // Add a custom JavaScript file to the page.
  $attachments[‘#attached’][‘library’][] = ‘custom_module/custom-scripts’;

  }Or hook_preprocess_page():
/**
* Implements hook_preprocess_page().
*/
function custom_module_preprocess_page(&$variables) {
  // Adding stylesheet to the page.
  $attachments[‘#attached’][‘library’][] = ‘custom_module/custom-styles’;
}Similarly, with different preprocess functions we can attach a library using the #attached render array property like:
/**
* Implements hook_page_attachments_alter
*/
function custom_module_attachments_alter(array &$page) {
  // Get the current path.
  $path = $current_path = Drupal::service(‘path.current’)->getPath();
  // If we’re on the node listing page, add our retro library.
  if ($path == ‘/node’) {
    $page[‘#attached’][‘library’][] = ‘custom_module/custom-styles’;
  }
}3. Inside a Twig template file:
Use attach_library() in twig template.
{# Attach a CSS library #}
{% attach_library(‘my_theme/global-styling’) %}

{# Attach a JavaScript library #}
{% attach_library(‘my_theme/global-scripts’) %}Final Thoughts
Assets Library in Drupal (versions 8 and above) has a profound impact on web development. It centralizes the management of CSS and JavaScript files within modules or themes, ensuring consistency and ease of maintenance across a website or application. By bundling these assets together, developers can efficiently control the presentation and functionality of their digital creations. If you’re looking to implement fantastic features of Drupal like this one in your next project, we have a team of Drupal experts who can help you. We’d love to talk!

Read more

Related Posts:

  • Specbee: Mastering Drupal 9 Layout Builder: A Comprehensive Guide to Effortlessly Customize Your Website's Design
    Specbee: Mastering Drupal 9 Layout Builder: A…
  • Envato Tuts+: Top 20 Most Usable Content Management Systems
    Envato Tuts+: Top 20 Most Usable Content Management Systems
  • Specbee: How to Create a Custom Module and add CSS Libraries in Drupal 9
    Specbee: How to Create a Custom Module and add CSS…
  • Specbee: Getting Started with Layout Builder in Drupal 9 - A Complete Guide
    Specbee: Getting Started with Layout Builder in…
  • Specbee: How to create and apply a patch with Git Diff and Git Apply commands for your Drupal website
    Specbee: How to create and apply a patch with Git…
  • Specbee: The Ultimate Guide to Jumpstart your Drupal Contribution Journey
    Specbee: The Ultimate Guide to Jumpstart your Drupal…

Recent Posts

  • [TUT] LoRa & LoRaWAN – MikroTik wAP LR8 kit mit The Things Network verbinden [4K | DE]
  • Mercado aguarda Powell e olha Trump, dados e Haddad | MINUTO TOURO DE OURO – 11/02/25
  • Dan Levy Gets Candid About Learning How To Act Differently After Schitt’s Creek: ‘It’s Physically…
  • Building a Rock Shelter & Overnight Stay in Heavy Snow 🏕️⛰️
  • Les milliardaires Elon Musk et Xavier Niel s’insultent copieusement

Categories

  • Android
  • Linux
  • News
  • Open Source
©2025 Open World News | Powered by Superb Themes
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept All”, you consent to the use of ALL the cookies. However, you may visit "Cookie Settings" to provide a controlled consent.
Cookie SettingsAccept All
Manage consent

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.
CookieDurationDescription
cookielawinfo-checkbox-analytics11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functional11 monthsThe cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessary11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-others11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performance11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policy11 monthsThe cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.
Functional
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytics
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
Advertisement
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.
Others
Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.
SAVE & ACCEPT