0

Drupal 7.x, Garland theme.

I am writing a module that depends on jQuery. I am seeing that when an anonymous visitor comes by that jQuery isn't being loaded. How do I load jQuery from my module?

I am not really a Drupal developer. This is my first module. I want to maintain Core as is (no hacking) for easy updates and I don't want to change themes from Garland, so I don't really want to edit the theme to force jQuery.

Thanks.

2 Answers 2

0

See Added methods to avoid loading jQuery and related JavaScript libraries on all pages when they are not needed.

Starting from Drupal 7.36, Drupal could not load jQuery to the page.

If you are adding JavaScript from your module, it means you are doing one of the following:

In both the cases, you can force Drupal to load jQuery.

drupal_add_js('path/to/some/javascript-library-needing-jquery.js', array('requires_jquery' => TRUE));
$build['#attached']['js'][] = array(
  drupal_get_path('module', 'mymodule') . '/javascript-library-needing-jquery.js' => array('requires_jquery' => TRUE)
);

Notice that, normally, calling drupal_add_js() or adding $build['#attached']['js'] is sufficient for making Drupal load jQuery, but if another module set 'requires_jquery' to FALSE, or if the settings.php file contains a $conf['javascript_always_use_jquery'] = FALSE; line, then jQuery will not be loaded. Only when your module is setting 'requires_jquery' to TRUE with one of the methods I described, you are sure the jQuery library is loaded from Drupal.

Notice that, in either cases, if none of the modules (or the theme) is adding JavaScript code to the page through drupal_add_js(), #attached, or the scripts directive in a .info file, Drupal will not load the jQuery library. This means that, if you are hard-coding the link to an external JavaScript file in a template file, Drupal will not know JavaScript code is being used, and it will not load the jQuery library found in the misc directory of the Drupal root directory.

1
  • Thank you, I discovered drupal_add_js() on my own yesterday afternoon. I have it working.
    – Rob Brandt
    Jul 20, 2017 at 16:36
0

jQuery should be available to you right out of the box in D7 if I remember correctly. But you need to use jQuery(...) instead of $(...). If jQuery is not being included for some reason, try using drupal_add_js().

See Drupal 7 JavaScript API documentation for more information.

2
  • You can use $ as long as it is passed into the function.
    – Kevin
    Jul 19, 2017 at 17:22
  • Yes, I am using jQuery().
    – Rob Brandt
    Jul 19, 2017 at 18:33

Your Answer

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

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