dataLayer race condition
robflaherty opened this issue · comments
JS error if dataLayer.push()
is called before GA converts dataLayer
from an array to a function.
dataLayer
shouldn't be touched by GA - it's the array-like data object used by GTM. On a page without GTM included, typeof(dataLayer); -> "undefined"
You should be able use the standard dataLayer = dataLayer || []
pattern to initialize it and avoid a race condition on the push
method if you need to push something onto it ahead of GTM being initialized but can't guarantee the order in which those things happen.
It seems like the real potential risk for a race condition is here since you aren't checking for the presence of the object you're firing an event to on the actual firing of the event. I think this might also cause a problem if you safe-initialized dataLayer
as above and it had type "object"
with a valid method push()
Hi,
Sorry, I left the bug description brief because this was just a reminder for myself. :)
The problem was this line: standardEventHandler = dataLayer.push;
which works after GTM redefines dataLayer but not before when it's still an array. Simply wrapping it like this should fix:
standardEventHandler = function(data) {
dataLayer.push(data);
}
Testing now and will push to master later today. Thanks.
btw, much of this needs to be rewritten. right now i just wanted to get a quick fix out. when i rewrite it i agree it'd be smart to make this more robust and check for the method presence before firing the event.
Cool - thanks again for maintaining this library.