How do we make a web page to execute a JavaScript function immediately after Google Analytics creates/updates all its cookies and the page DOM is loaded.
Can it be done with jQuery? How?
This function gets information from the GA cookies. I’ve tried executing the function when the page DOM is loaded, but sometimes GA has not created it’s cookies yet.
There are 2 elements here: First, DOM ready with jQuery. That’s easy:
The way to ensure that your function executes after Google Analytics has created its cookies (once it had implicitly executed
initData()) is to pass the function within the_gaqarray queue so that it gets executed after the_trackPageviewcall.For example:
So, you could put the following anywhere on the page below
_gaq.push(["_trackPageview"])(or after any_gaqcall that initiates the cookies; most commonly,_trackPageview,_trackEvent, and_setCustomVar.Now to ensure that the function both executes after DOM Ready and that
initData()is implicitly called, you can either do this:Or:
They both do what you’re looking for, though it sounds like the first one better fits your mental model of what you’re trying to accomplish.