Add new comment

Drupal 7 update jQuery.once: jquery.once polyfill

Difficulty: 
Piece of Cake

In this post I will share a quick tip on how to upgrade the jquery.once plugin in Drupal 7 without breaking current code.

Drupal 7 ships with jquery.once plugin version 1.2 that dates from 2013. For a project we needed to make code targeting the old 1.x and the 2.x work at the same time. In our case this was core javascript written for 1.x working with some code of ours designed for jquery.once 2.x.

The solution is easy: upgrade the core jquery.once to 2.x and add a polyfill to make it backwards compatible.

Just as a reference implementation create a module with two files:

js/jquery.once.js: the new 2.x jquery library

js/jquery.once.polyfill.js: the backwards compatibility layer (https://github.com/david-garcia-garcia/jquery.once.pollyfill)

Then use a hook to replace the core library and add the pollyfill:

/**
 * Implementes hook_js_alter.
 */
function {MYMODULE}_js_alter(&$javascript) {
  // Replace core jquery.once with a newer version....
  if (isset($javascript['misc/jquery.once.js'])) {
    $javascript['misc/jquery.once.js']['data'] = drupal_get_path('module', '{MYMODULE}') . '/js/jquery.once.js';
    // And a pollyfill to make it backwards compatible...
    $pollifylpath = drupal_get_path('module', '{MYMODULE}') . '/js/jquery.once.pollyfill.js';
    // Clone with new array
    $javascript[$pollifylpath] = $javascript['misc/jquery.once.js'];
    $javascript[$pollifylpath]['data'] = $pollifylpath;
  }
}

This is a quick workaround. You might be willing to use the libraries module to better approach the issue.