I develop an web application with preact. The total size of the webapp is about 30KB gzipped (Google Analytics is about 14KB). I want to add google analytics but I dont want that google analytics slows down the initial page load. The recommended method to include analytics.js () is
<!-- Google Analytics -->
<script>
window.ga=window.ga||function(){(ga.q=ga.q|| .
[]).push(arguments)};ga.l=+new Date;
ga('create', 'UA-XXXXX-Y', 'auto');
ga('send', 'pageview');
</script>
<script async src='https://www.google-analytics.com/analytics.js'> .
</script>
<!-- End Google Analytics -->
This works fine, but the analytics.js gets downloaded before my other stuff gets downloaded. Im pretty sure that this affects the page load as you can see in this picture)
What is the recommend way to download analytics after the page finished loading. (In my case after 'menu' gets downloaded)
I know this is old, but you could add the defer attribute instead of the async attribute to your tag. Async will download the file asynchronously, but it still blocks the main thread while it's running the javascript. Defer will also download asynchronously, but will wait to run the javascript until the HTML parses. This is one of many articles that explains the difference between async and defer
If you really don't want the GA affecting load speeds, you could add an event listener that waits for the window 'load' event before injecting the GA script tags. That is probably overkill for a 30KB web app, but GA will have almost no affect on your page loads.
GA shouldn't be slowing down your website right now
Your script is async, which means it's not blocking the browser from carrying on with other tasks. Accordingly, from the trace screenshot you gave, we can indeed see that while analytics.js is being requested, the browser is making other concurrent requests (bundle.js, ,menu), so you're good.
Loading GA after page load
If you still want to defer loading of GA after page load for best practices, just call GA later:
Using Javascript: Pure JavaScript equivalent of jQuery's $.ready() - how to call a function when the page/DOM is ready for it
Using a Tag Manager: for instance with Google Tag Manager, use the Window Loaded trigger which fires when the browser is done loading the page: https://productforums.google.com/forum/#!topic/tag-manager/xOMFkfH0U4k;context-place=forum/tag-manager
Related
I am implementing google analytics for the first time. Here are the steps I took.
I went to analytics.google.com and created an account. Then I created a "property". After that I created a "Data Stream" for my website and got a "Measurement ID which starts with a G-XXXXXXX. Then I implemented the following code in the header (before any other css or js calls)
<!-- Google Analytics -->
<script>
window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
ga('create', 'G-XXXXXXX', 'auto');
ga('send', 'pageview');
</script>
<script async src='https://www.google-analytics.com/analytics.js'></script>
<!-- End Google Analytics -->
When I look at the network tab, I can see that the call was made:
Request URL: https://www.google-analytics.com/j/collect?v=1&_v=j96&a=316116739&t=pageview&_s=1&dl=https://mywebsite.com&ul=en-gb&de=UTF-8&dt=My Website Title&sd=24-bit&sr=1920x1080&vp=1920x577&je=0&_u=ABC~&jid=1234&gjid=1234&cid=1234.1234&tid=G-XXXXXXX&_gid=1234.1234&_r=1&_slc=1&z=1234
Method: Post
Status Code: 200
However when I look at google analytics, it says "Data collection isn't active for your website".
I waited 24 hours to ensure it is not some delay problem but there is still no data and there have been visitors on the website, at the very least myself.
Is there a step I missed or maybe it could be a configuration issue? I haven't been able to find any clues as to why it might not be working. Any help is most appreciated.
Note: The values above in Request URL have been modified to remove any sensitive information. All the parameters are there, just values have been changed to ABC and 1234 as its not necessary to see those.
If you want to track with GA4 (G-xxxxxxxx)
You need to use gtag.js for it.
ga.js is not support for GA4
Here is the document
I've ran into a problem that I've never seen before and I'm in dire need of help on this one.
I've setup some GA4 tags for a single-page application which caused my UA tags to change status to "Still Running" and not sending data to my UA properties. This only happens to the UA tags fired after the GA4 configuration tag is fired:
screenshot of the second virtual pageview Data Layer event fired on the website
There aren't any tags affected by our GA4 tag besides the UA tags. GA4 event tags fire completely fine too.
Other information: I'm quite experience with GTM. We're firing our tags on dataLayer events that signify virtual page views. I've tried everything I could think of to check if I could run both UA & GA tags at the same time, but nothing worked.
I thought that the ga() method might've been hijacked so I even tried to check that by posting on the console the following:
console.log(window[window['GoogleAnalyticsObject']].answer);
But the response was "42" which means that the analytics.js library is still working with the global method (thanks Simo Ahava for the tip).
P.S. I'm not running Google Optimize on the website which is a well-known thing that might cause this issue.
Best regards,
Daniel
Do you use a CutomTask in your UA settings?
I had the same issue and couldnt find the solution, I have found that a CutomTask running a clientID event before the UA payload was the reason to this problem.
I'm trying to introduce Google Analytics in a sort of desktop app that all loading files are done through file:// not http or localhost (because most of the time it works offline). Any attempt to track app uses with Google Analytics or Google Tag Manager wasn't work.
For example, I've used:
ga('create', 'UA-XXXXX-Y', 'auto');
ga('set', 'checkProtocolTask', null);
ga('set', 'checkStorageTask', null);
ga('send', 'pageview');
As explained here (adding ga('set', 'checkStorageTask', null);
) with no results.
Has anybody deal with this situation?
I run a very quick test. ga('set', 'checkStorageTask', null); did nothing for me, instead I found it necessary to set storage to none on tracker creation (which makes sense, since you cannot set cookies with the file protocol). This also means that you probably won't have session tracking, since each hit generates a new ID.
ga('set', 'checkProtocolTask', null) seems necessary - else the debugger complains (naturally) that file is not a valid protocol.
After that data was sucessfully sent, but did not show up in the realtime view. I suspected that maybe the reporting engine does not like the file protocol and set the "location" field with a correct protocol. So I ended up with:
ga('create', 'UA-XXXXXX-5' , {'storage':'none'});
ga('set', 'checkProtocolTask', null);
ga('send', 'pageview' , {'location' : document.location.href.replace('file','http') });
and that displayed in the realtime reports. This was a real quick test, so you need to verify this independently. Notice that you do not need to set a cookie domain (the "auto" argument in your code example) since you cannot set a cookie in any case (there is no domain to set the cookie to).
Also if you work offline for most of the time GA will not work (you need to load the analytics.js file and you need sent calls to the tracking server), but then you are probably aware of that.
I have a special situation where the sites visitors can access the page from a certain domain but no others. So HTML and assets are no problem as long as they are stored on the server. Google Analytics on the other hand requires a download of analytics.js from Googles servers, which is impossible.
So I'm looking for a way to proxy this. The webserver itself has internet access and could relay the trafic. To report to Google about my page view, a single pixel GIF is downloaded from Google, described here: https://developers.google.com/analytics/resources/concepts/gaConceptsTrackingOverview
I think it would be kind of easy to get all the parameters in the GIF and use the measurement protocol to report to Google from the server - but the hard bit is to get all this info to the server. To download analytics.js and modify it to go to my own server seems to me as a hack that ain't future proof at all. To just get the current page from the user to the server is not a big deal, but we would like to get the user id, browser version and everything you get with Analytics.
How would you do it? Do you find a solution for this?
Update: Google has since released server-side GTM, which allows you to proxy requests and scripts through a custom domain. In most use cases I can imagine, this would be the much superior solution to a dyi proxy.
As pointed out in my comment the utm.gif is no longer used. Google Analytics has completely switched to the Measurement Protocol and data is now sent to the Endpoint for the Measurement Protocol at google-analytics.com/collect. Actually this still return a transparent pixel since calling an image with parameters is a probate way of transmitting informations across domain boundaries.
Now, you could just the Measurement Protocol to implement your own Google Analytics tracker.
To quote myself:
Each calls includes at least the ID of the account you want to send
data to, a client id that allows to group interactions into sessions
(so it should be unique per visitor, but it must not identify a user
personally), an interaction type (pageview, event, timing etc., some
interactions types require additional parameters) and the version of
the protocol you are using (at the moment there is only one version).
So the most basic example to record a pageview would look like this:
www.google-analytics.com/collect/v=1&tid=UA-XXXXY&cid=555&t=pageview&dp=%2Fmypage
You probably would want to add the users IP (will be anonymized automatically) and the user agent.
However it sounds like you prefer to use the standard Analytics code to collect the data and relay the tracking call via your own server. While I haven't used the following in production I don't see any reason why it wouldn't work.
First you need the analytics.js file. Self-hosting the file is discouraged, but the given reason is that the code is updated sometimes by Google and if you host it yourself you might miss the updates. This can be remedied by setting up a cron job that downloads the file regularly to your server so you always have a current version.
Next you'd adapt the GA bootstrap function to load the code from your own server:
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.myserver.com/analytics.js','ga');
Now you have the code, but the tracking call will still be sent to the Analytics Server (i.e. in your case it won't be sent at all). So you need to re-route the call via your server.
To make this possible the Google (Universal) Analytics Code has a feature called "tasks". Tasks are functions within the tracking code in which the tracking call is being assembled.
It is possible to modify tasks by using the "set" function of the tracker object, using the taskname as parameter and passing a function that overwrites/overloads the task function.
The following is pretty much the example from the Google documentation (except I omitted the part where data is still being sent to Google - you don't need this at this point):
ga('create', 'UA-XXXXX-Y', 'auto');
ga(function(tracker) {
tracker.set('sendHitTask', function(model) {
var payLoad = model.get('hitPayload');
var gifRequest = new XMLHttpRequest();
var gifPath = "/__ua.gif";
gifRequest.open('get', gifPath + '?' + payLoad, true);
gifRequest.send();
});
});
ga('send', 'pageview');
Now this sends the data to a file called __ua.gif at your own server (if you need to send data cross-domain you can simply do a var ua = new Image; ua.src = gifPath + '?' + payLoad to create an image request).
The model parameter to the sendHitTask-function contains (apart from a lot of overhead) the payload, that is the assembled query string that contains the analytics data. You can then make your _ua.gif a script that proxies the request to the google-analytics.com/collect.
At this point the user agent will be your script and the IP adress will be that of your server, so you need to include &uip (User IP override) and &ua (User agent override) parameters ( https://groups.google.com/forum/#!msg/google-analytics-measurement-protocol/8TAp7_I1uTk/KNjI5IGwT58J) to get geo and technical information.
If you are feeling more adventurous you can override the buildHitTask instead and try and add the additional parameters there (more hassle probably since you'd need to get the IP address from somewhere).
For additional parameter see the reference for analytics.js and the Measurement Protocol.
I want to track clicks with google analytics. Is there any tutorial for this?
I use the following jQuery code to add event tracking, assuming, that all external links begin with http://:
$(document).ready(function() {
$("a[#href^='http://']:not(.internal)").addClass("external").bind('click keypress', function(event) {
var code=event.charCode || event.keyCode;
if(!code || (code && code == 13)) {
if(pageTracker){
pageTracker._trackEvent('outgoing', 'click', this.href);
};
};
});
GA doesn't auto-track external links, so you have manually call one of its functions on all your exit links. You can track it as a virtual page view or as a custom variable or event, passing the relevant information you want to track, to the GA functions (like the exit link url).
Depending on how your links are setup, you can easily setup an click event listener to trigger the GA function call. For example, if all of the exit links have a specific css class attribute associated with them then you can hook the click event to that.
If all of your exit links point to your php script and only pass an ID number to it or something (no actual exit url), then you will not be able to pass to GA the exit link url. If you are fine with just passing the ID then you can use that instead of the url and pass as the virtual url or custom variable value "/exit/[id]" or whatever else makes sense to you. And you can also look for the php script's url as a way to hook the click event to all your exit links, if there is no other unique identifier.
If none of this is an option and you have to do it server-side...then you're kind of out of luck on doing it the "easy" way. GA has an API for interacting with it via server-side code but it's only 1-way. You can use it to get information out of GA but you can't use it to put information into it.
However, what you CAN do is...when a request to GA is made, take a look at that request in Firebug > NET tab or in Charles Proxy or some other request sniffer program, or take a look at the GA's url in its noscript tag. The way it works is a request is made to the GA server and variables and values are appended to the url as a query string.
So what you can do is build a url like that and use cURL to make a request to the GA server...but here's the tricky part: you have to fool GA into thinking the request was made from a browser, not your server. So you need to make sure you send header information with the cURL request to make it look like a browser made the request. Ideally you will want to use whatever header information was sent to your server from the client so that GA can record the hit as if it were the user, so that reports can populate accordingly.
You could send the requests to your server, and your server could send the user a 301 redirect.
Your could then do server-side google analytics, by sending requests to http://www.google-analytics.com/utm.gif to google, like this project does: http://code.google.com/p/php-ga/
You can use this jQuery library to help with sending click events to GA:
https://github.com/spilliton/track_that