0

I have a controller with a route that has some javascript attached to it as a library. When logged in as any user (admin or standard) the JS loads just fine. When anonymous, the library file is loaded, but Drupal JS is not.

How the library is defined:

my_javascript:
  version: 1.x
  js:
    js/my_javascript.js: {}
  dependencies:
    - core/jquery

In the console the error says:

ReferenceError: Drupal is not defined

< anonymous > http://example.com/themes/custom/my_theme/js/my_javascript.js:7:3

< anonymous > http://example.com/themes/custom/my_theme/js/my_javascript.js:6:2

The lines in the JS the error is referring to are:

(function ($) {
  Drupal.behaviors.myScripts = {

This is the case for all browsers. JS works fine when logged in as any user, but when anonymous, Drupal's JS does not load.

2 Answers 2

10

The code in the question appears to be similar to what was done in Drupal 7. In Drupal 8, the dependencies for your javascript need to be explicitly defined and it is a good idea to pass them through the closure as well. You can read more about the Javascript API in Drupal 8 on the new documentation pages.

my_javascript:
  version: 1.x
  js:
    js/my_javascript.js: {}
  dependencies:
    - core/jquery
    - core/drupal



(function ($, Drupal) {
  Drupal.behaviors.myScripts = {};
)(jQuery, Drupal);
0

Solved by adding more dependencies to the library definition and adding a hook to add the JS again, and render libraries.

New library definition:

my_javascript:
  version: 1.x
  js:
    js/my_javascript.js: {}
  dependencies:
    - core/jquery
    - core/drupal.ajax
    - core/drupal
    - core/drupalSettings
    - core/jquery.once

Hook to render libraries:

function my_theme_preprocess_page(array &$variables) {
  $attachments['#attached']['library'][] = 'my_theme/my_javascript';
  \Drupal::service('renderer')->renderRoot($libraries);
}

Update: The hook was not needed, but adding the Drupal object in behaviors correctly for D8 was. Accepted another answer instead.

3
  • 2
    I'm not sure why you are calling drupal_render in your preprocess. You should not need to do any of that to add JavaScript code in your theme. You only need to add libraries.yml definition.
    – mradcliffe
    Dec 29, 2016 at 16:02
  • The is a hook specific for adding attachments. You should use it instead of hook_preprocess_page
    – Eyal
    Dec 29, 2016 at 16:09
  • @mradcliffe you're right
    – CR47
    Dec 29, 2016 at 16:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.