function google_optimize_page_attachments in Google Optimize 8
Implements hook_page_attachments().
Attach JavaScript to the appropriate scope/region of the page.
File
- ./
google_optimize.module, line 180 - google_optimize.module
Code
function google_optimize_page_attachments(array &$attachments) {
if (!google_optimize_hide_page_active()) {
return;
}
// Create the container string 'GTM-XXXXXX':true,'GTM-YYYYYY':true.
$container_ids = google_optimize_container_ids();
$container_ids = array_map(function ($value) {
return "'" . trim($value) . "':true";
}, $container_ids);
$container_str = implode(',', $container_ids);
$class_name = google_optimize_hide_page_class_name();
$timeout = google_optimize_hide_page_timeout();
$js = sprintf("(function(a,s,y,n,c,h,i,d,e){s.className+=' '+y;h.start=1*new Date;\nh.end=i=function(){s.className=s.className.replace(RegExp(' ?'+y),'')};\n(a[n]=a[n]||[]).hide=h;setTimeout(function(){i();h.end=null},c);h.timeout=c;\n})(window,document.documentElement,'%s','dataLayer',%d,\n{%s});", $class_name, $timeout, $container_str);
// Insert the hide page snippet immediantly before the
// Google Analytics script. Can't splice to begining of html_head
// As datalayers-js may be 1st and this would redefine dataLayer.
foreach ($attachments['#attached']['html_head'] as $key => $tag) {
if (count($tag) && $tag[1] == 'google_analytics_tracking_script') {
array_splice($attachments['#attached']['html_head'], $key, 0, [
[
[
'#type' => 'html_tag',
'#tag' => 'script',
'#value' => $js,
'#attributes' => [],
],
'google-optimize-hide-page-js',
],
]);
break;
}
}
$css = '.' . $class_name . ' { opacity: 0 !important} ';
$attachments['#attached']['html_head'][] = [
[
'#type' => 'html_tag',
'#tag' => 'style',
'#value' => $css,
],
'google-optimize-hide-page-css',
];
}