'Adding items to the same datalayer object after page load
On my site, I have a page object that contains multiple bits of information about the page that is currently being viewed that I want to push to the datalayer. (Title, description, page type, etc).
Most of this information is available on page load however there is a piece of information that is only available after an ajax request. Is it possible to push this object to the datalayer as an incomplete object when it is available on the page multiple times and have GTM recognize that it is the same object and combine it internally?
I want to do something like this:
<!-- within <head> (available on page load)-->
dataLayer.push({
"page":{
"title": "my_page_title",
"description": "my_page_description"
});
(Page completes rendering)
<!-- part of AJAX success response -->
dataLayer.push({
"page":{
"purchasable": true
});
and have GTM interpret it the same as if I were to do:
dataLayer.push({
"page":{
"title": "my_page_title",
"description": "my_page_description",
"purchasable": true
});
Currently, I am pushing the complete page object to the datalayer after the ajax response but there is a request to me to try and move everything to the page load. Moving to page load is more complicated so I'm trying to see if this would be possible as an alternative solution.
Within GTM, we have tags in place to map this page object to a custom dimension. I'm not part of the team that does this configuration though so I don't have much information regarding that part.
Solution 1:[1]
The GTM merges objects automatically in its internal data model, when you create a "Version 2" DataLayer Variable.
Hence, you could create a DataLayer variable that accesses the key page
. In your code you can emit a custom event when all the page data is available:
// Page Load
dataLayer.push({
page: {
title: "my_page_title",
},
});
dataLayer.push({
event: "page_info",
page: {
purchasable: true,
},
});
When you trigger a tag on your custom event page_info
that references the dataLayer variable DLV - page
, it will have access to the combined object.
{
title: "my_page_title",
purchasable: true
}
You can use the GTM debug mode to test this.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | ptts |