我使用「跟蹤代碼」模塊(https://www.drupal.org/project/tracking_code)來添加我的跟蹤代碼片段。Drupal |緩存頁面中未緩存的JS cookie /跟蹤代碼算法
我將這些代碼添加到After <BODY>
。
我也有我自己的跟蹤cookie,它包含userID
。
目標: 設置userID
每個跟蹤代碼段
問題:我已經啓用了我的緩存,所以這些片段代碼緩存。這意味着我無法用PHP解析cookie並設置全局js變量,這些變量可以在每個片段中訪問。
解決方案: 用JavaScript解析cookie,所以即使代碼被緩存,變量仍然會被更新。
問題: 通常的Drupal的JS,如:
(function($) {
Drupal.behaviors.user_cookie = {
attach: function (context, settings) {
...
//Im getting some variables from PHP here and using them
}
}
})(jQuery);
被執行爲時已晚,這意味着定義的變量有沒有在跟蹤代碼段可用。
SOLUTION:使用下面的代碼,我可以設置js的變量,它們可以從片段進行訪問
(function ($, Drupal, window, document, undefined) {
// Is executed on time!
// How to get variables from php here??
})(jQuery, Drupal, this, this.document);
問題:我不能再得到一些靜態變量(可以被緩存)從PHP,使用的代碼:
function user_cookie_page_build(&$page) {
drupal_add_js(array('user_cookie' => array('someVariable' => $someValue)), 'setting');
drupal_add_js(drupal_get_path('module', 'user_cookie') . '/js/user_cookie.js');
}
SOLUTION(替代方法):執行內聯腳本在head
設置變量,但我不喜歡這種方式。
drupal_add_js('Drupal.user_cookie.cookieName = "'
. variable_get('user_cookie_fname') . '";',
array(
'type' => 'inline',
'scope' => 'head',
'weight' => 0
)
);
drupal_add_js(drupal_get_path('module', 'ft_user_cookie') . '/js/ft_user_cookie.js');
如果有人有更好的解決方案(Ajax不是我的情況),請告訴我!