How to personalize the Ajax loader

2 minutes

Since Drupal 8.6, it is possible to overwrite the HTML created by the Ajax loader and this is very useful for personalizing its appearance. In this article, I will show you how to do it from your site's theme.

Defining the Library 

The first step is to define a new library that calls the necessary JavaScript, which can be done in your theme's .libraries.yml file and would look like this:

throbber:
  js:
    js/ajax-loader.js: {}
  dependencies:
    - core/drupal

Here, we are defining a library called `throbber` in your theme.

Extending the drupal.ajax Library

To ensure that Drupal loads your library along with the core Ajax library, you need to extend it and you can do this very simple in your theme's .info file by adding the following lines, remembering to change the word `your-theme` to your theme's name:

libraries-extend:
  core/drupal.ajax:
    - your-theme/throbber

What do we put in ajax-loader.js? 

We define two functions that replace the core functions responsible for creating the loader. These are:

  • ajaxProgressThrobber - Loader that appears when you click on some button and is usually next to the same.
  • ajaxProgressIndicatorFullscreen - Loader that usually appears centered on the screen and is common in the Ajax views.

The JavaScript code in the ajax-loader.js file would look like this:

(function (Drupal) {
  Drupal.theme.ajaxProgressThrobber = function () {
    return "<div class="loader-wrapper"><div class="loader is-loading">" + Drupal.t('Loading &amp;hellip;', {}, {
      context: 'Loading text for Drupal cores Ajax throbber (inline)'
    }) + "</div></div>";
  };

  Drupal.theme.ajaxProgressIndicatorFullscreen = function () {
    return "<div class="loader-wrapper"><div class="loader is-loading"></div></div>";
  };
})(Drupal);

As you can see in the first function, we use Drupal.t to make the text that appears translatable, and in the second, I decided to leave it without text to only have the elements for personalization through CSS.

Conclusion

Although it is possible to alter the Ajax loader only by using CSS, this way of doing it allows us to also change the generated HTML and gives us more control to make it cleaner.

Jidrone Drupal Developer
J. Ivan Duarte
Drupal Senior Developer

Share