Drupal 8 now uses libraries concept to load javascript into the Drupal 8 website. Libraries are defined in the libararies.yml file in the root directory of the module or theme folder.

Following will be the general file structure to add a js file to module

We have added the routing.yml file as below

hello_js:
    path: "hello_js/info"
    defaults: 
        _controller: Drupal\hello_js\Controller\HelloJsController::info
    requirements:
        _permission: 'access content'

 

Let us define the libraries.yml file in the following way.

hello_js:
    js:
        js/hello_js.js: {}
    dependencies:
        - core/jquery

Here in the libraries.yml file we need to define the library name which contains details about the Javascript File we intended to add and its dependencies.

Now we have defined our library, but we need to add the Javascript file now. It is added to js/hello_js folder. I have added the Javascript in such a way that it makes the page title red.

(function ($, Drupal) {
    Drupal.behaviors.fifth_module = {
        attach: function (context, settings) {
            $('.title', context).css("color", "red");
        }
    };
})(jQuery, Drupal);

 

Now to add the Javascript to a specific page we need to alter the attached property in the controller class.

namespace Drupal\hello_js\Controller;
use Drupal\Core\Controller\ControllerBase;

class HelloJsController extends ControllerBase{
    public function info(){
        return [
            '#title' => 'This is Javascript Title',
            '#type' => 'markup',
            '#markup' => $this->t("This is an example to show Javascript Loading"),
            '#attached' => array(
                'library' => array(
                    'hello_js/hello_js',
                )
            )
        ];
    }
}

This loads the hello_js.js Javascript to the only when hello_js/info path is accessed.

 

Suppose we want to load Javascript to every page that’s accessed. We need to call the hook_page_attachments() in our module file.

function hello_js_page_attachments(&$page){
    $page['#attached']['library'][] = 'hello_js/hello_js';
}

This will add the hello_js.js Javascript file to every page on the Drupal website.

 

There are some more complicated loading can be done using the hook_page_attachements() hook , that allow Javascript to load conditionally.

Leave a Reply

Your email address will not be published. Required fields are marked *