Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
Ive always wrapped my jquery code in a dom ready function. However looking at the js file provided by my zen theme, do I actually need to do this? Is the function defined already preventing the code from firing before the page has loaded?
(function ($, Drupal, window, document, undefined) {
// To understand behaviors, see https://drupal.org/node/756722#behaviors
Drupal.behaviors.my_custom_behavior = {
attach: function(context, settings) {
// Place your code here.
}
};
})(jQuery, Drupal, this, this.document);
Comments
Comment #1
joelhsmith CreditAttribution: joelhsmith commentedYou do not need to add the jQuery document.ready function inside Drupal.behaviors. The Drupal.behaviors object will automatically run when Drupal knows the page is ready for manipulation.
Drupal.behaviors object is way more efficient than just using the document.ready because it does not ask jQuery to traverse the DOM a second time (Drupal has already done that once for us).
Also note that using the context argument helps with performance. If some new content is added to the page via ajax the code will only run on that part to the DOM.
Glad to see you are using the Drupal.behaviors object instead of just pasting in document.ready. Thats the pro thing to do :-)
Comment #2
JohnAlbin