diff --git a/includes/plugins.inc b/includes/plugins.inc
index 9077d38..b470668 100644
--- a/includes/plugins.inc
+++ b/includes/plugins.inc
@@ -173,15 +173,36 @@ class panels_cache_object {
     $start = $this->js;
     $this->js = array();
 
+    // Use the advanced mapping function from Drupal >= 7.23 if available.
+    $array_mapping_func = function_exists('drupal_array_diff_assoc_recursive') ? 'drupal_array_diff_assoc_recursive' : 'array_diff_assoc';
+
     // If there are any differences between the old and the new javascript then
     // store them to be added later.
-    if ($diff = array_diff_assoc($js, $start)) {
-      $this->js = $diff;
-    }
-
-    // Special case the settings key and get the difference of the data.
-    if ($settings_diff = array_diff_assoc($js['settings']['data'], $start['settings']['data'])) {
-      $this->js['settings'] = $settings_diff;
+    if ($diff = $array_mapping_func($js, $start)) {
+      // Iterate over the diff to ensure we keep the keys on merge and don't add
+      // unnecessary items.
+      foreach ($diff as $key => $diff_data) {
+        // Special case the settings key and get the difference of the data.
+        if ($key === 'settings') {
+          // Iterate over the diff to ensure we keep the keys on merge and don't
+          // add unnecessary items.
+          if (isset($diff[$key]['data'])) {
+            foreach ($diff[$key]['data'] as $settings_key => $settings_data) {
+              // Merge the changes with the base to get a complete settings
+              // array.
+              $this->js[$key]['data'][] = drupal_array_merge_deep($settings_data, $diff[$key]['data'][$settings_key]);
+            }
+          }
+        }
+        else {
+          $this->js[$key] = $diff_data;
+          // Check if the key was present already and if so merge the changes
+          // with the original data to get the full settings array.
+          if (isset($start[$key])) {
+            $this->js[$key] = drupal_array_merge_deep($start[$key], $this->js[$key]);
+          }
+        }
+      }
     }
 
     // And for tokens:
@@ -213,7 +234,7 @@ class panels_cache_object {
           drupal_add_js($args['data'], $args);
         }
         else {
-          foreach ($args as $setting) {
+          foreach ($args['data'] as $setting) {
             drupal_add_js($setting, 'setting');
           }
         }
