0

I would think there would already be a straight forward answer to my very simple question however I couldn't find it. Forgive me if this is a duplicate.

My question is:

If I only want my jQuery to run on normal page load and don't care about when data is loaded by AJAX, should I still be using Drupal.behaviors instead of $(document).ready ? If so should I be doing anything with the context and settings parameters?

I'm mostly adding/ removing classes however there a couple of instances where I'm appending/ removing elements.

Thank you.

  • 2
    Yes, Drupal.behaviors and .once(), see drupal.org/docs/8/api/javascript-api/javascript-api-overview. – leymannx Aug 28 '19 at 15:39
  • 3
    Probably a duplicate of drupal.stackexchange.com/a/244501/15055 – leymannx Aug 28 '19 at 15:41
  • 2
    Yes, ALWAYS use behaviors, e.g. because of BigPipe module – Hudri Aug 28 '19 at 16:14
  • It seems like you don't know what to do with context because your js code is not attaching anything to the DOM. Then the answer is no, you don't need to use Drupal.behaviors. You could make things clearer by explaining what your js code is doing instead. – 4k4 Aug 28 '19 at 16:16
  • 1
    "I'm mostly adding/ removing classes however there a couple of instances where I'm appending/ removing elements." Then use Drupal.behaviors as explained in the linked doc. – 4k4 Aug 28 '19 at 17:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.