Skip to content

Convert js to vanilla js.

Merge Request: Fix ad module frontend — use proper GET serialization & lazy-load ads

The current ad behavior attempts to send a request body with a GET request, which is invalid and can prevent ads from loading correctly. This MR replaces that pattern with standards-compliant query serialization and adds viewport-based lazy loading to reduce unnecessary requests and improve performance.

Changes

  • Replaces jQuery AJAX with fetch + URLSearchParams (vanilla JS), encoding parameters in the query string rather than the request body.
  • Adds lazy loading via IntersectionObserver with a graceful fallback when the API isn’t available.
  • Calls Drupal.attachBehaviors(el) after injecting returned ad markup so behaviors initialize on newly added DOM.
  • Preserves support for parsing the arguments attribute as JSON or key=value;key2=value2 formats.
  • Continues to use Drupal behaviors and once() to prevent duplicate processing.

Steps to reproduce

  1. Place an ad container (e.g., an element with id and ad-content selector) on a page.
  2. Observe network traffic: the current code attempts to send a GET request with a request body, which is non-standard and may fail.
  3. With this patch applied, ads load correctly, and requests are issued only when the element comes into (or near) the viewport.

Proposed resolution

  • Use vanilla JS with fetch and querystring serialization for all request parameters (e.g., ads[id][placement], uid, url, etc.).
  • Lazy-load ad content using IntersectionObserver and a small rootMargin to prefetch just before visibility.
  • Re-attach Drupal behaviors to the injected HTML container.

Compatibility notes

  • No dependency on jQuery for the ad behavior.
  • If IntersectionObserver isn’t supported, the code falls back to immediate loading.
  • Query serialization mirrors how jQuery would send nested data (e.g., ads[my-id][placement]), matching typical PHP parsing on the server.

Testing

  • Verify ads render and behaviors initialize on modern browsers.
  • Test in an environment without IntersectionObserver to confirm fallback works.
  • Confirm that server-side receives the expected nested parameters under $_GET.

Remaining tasks

  • Review and confirm serialization matches the module’s controller expectations.
  • Cross-browser test with/without IntersectionObserver.

Merge request reports

Loading