We are using Google Analytics for our site that has huge traffic. We are in trouble with some interesting -and surely not good- changes in stats since last 50 days(started on April 13). Bounce rates has doubled, our "time on site" value decreased about 5 minutes and unique visitor counts unexpectedly increased very high. In addition, our pageview stats has no change. We are investigating cause of this issue for several days. We know, these symptomps shows us there is a problem about user sessions. We are loosing user's analytics sessions on somewhere on our site. We got a tip:
We noticed that, our search page has 2.5x more value for "landing page" since 50 days. We are using _trackEvent method for tracking some user interactions on our search page. When we followed the utmb cookie of google analytics(that, as we know, it stores user session for analytics), we noticed that, when we track an event, utmb cookie value changes.
So, the question is, is it normal to tracking events changes to utmb cookie? May this problem be the reason we live in?
UPDATE
We are using ga.js as self-hosted on our servers. Our tracking code is so simple:
_gaq.push(['_setAccount', 'UA-235XXX-1']);
_gaq.push(['_setDomainName', '.ourdomain.com']);
_gaq.push(['_setAllowHash', false]);
_gaq.push(['_trackPageview']);
UPDATE 2
We removed setAllowHash parameter and started to host ga.js on google as default usage. Problem still continues.
I'm having exactly the same problem. It also started on 14th April 2012, bounce rates going up, new visits also, shortening Time on site and lowering pages per visit...
Pageviews remain the same, which means that for some reason, users are 'losing' __utma cookie, responsible for tracking the user as unique.
One thing I found interesting through GA - in my case this problem does not show for Opera 11.64. It holds its previous value of about 14% bounce rate. Other browsers (mainly new versions of Firefox and Chrome) went through the roof (bounce rate of 65-90%).
I am talking about a website with couple of hundreds of thousands of visits...
Tommorow I will try change a few things, and post back if I find anything useful.
UPDATE
I have updated the code to the new one
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'XX-XXXXXXXX-X']);
_gaq.push(['_setDomainName', 'example.com']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
instead of the old one
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
try {
var pageTracker = _gat._getTracker("XX-XXXXXXXX-X");
pageTracker._setDomainName(".example.com");
pageTracker._trackPageview();
} catch(err) {}</script>
The difference in _setDomainName is that in new code it doesn't have the leading dot(.) in domain name, and there seems to be the problem with the old code.
I must add that I'm not having any trouble with the other website that doesn't have _setDomainName part, and still is running the old code.
I also found a blog post about the same problem:
http://diegoscataglini.com/2010/08/17/118/google-analytics-setdomain-beware/
Anyway, now things are back to normal. Bounce rate back to 11%, time on site going up as well as Pages / Visit.
When you change the code cookies will be recreated for all users, making them new visitors coming directly to your site. In a day or two (depending on number of visits), as people use your site as they do normally, statistics go back to normal.
I had to wait couple of days before reporting back, and I hope this will solve your problem too.
Thinking aloud, perhaps this could be attributed to a popular browser suddenly supporting "do not track" or GA suddenly respecting the setting.
Updating the utmb cookie is an expected behavior for _trackEvent -- from the Event Tracking API docs:
By default, the event hit sent by _trackEvent() will impact a
visitor's bounce rate.
One place to loose session data is with subdomains -- For example, if you've got a mixture of www.domain.com & domain.com links on your site. If you're not using it already, you could try adding _setDomainName before the _trackPageview call:
_gaq.push(['_setDomainName', '.yourDomain.com']);
This is normal. The utmb cookie stores the hit count for a session and when you track an event or a pageview the hit count is increased by one.
This is used in GA internals to control some limits.
Once this counter reaches 500 it won't send any more hits for that session. Each session in analytics can only have 500 hits.
UPDATE: 2012-06-12
Based on the code you posted I have a few concerns:
You should NEVER self-host ga.js. This file changes as new features are added to GA. This might explain the bounce-rate changes or might not. You might be sending data that is not what ga is expecting anymore as they might have changed the protocol a little bit.
_setAllowHash is deprecated by now. If you're using now you should keep using it, but if you have any pages without that call that might be causing cookies to be reset. So if all your pages use that, keep it that way, if some pages use and some pages don't, than remove and make sure not a single page has it anymore. You need to be consistent with GA settings.
Related
Ok it's 19 Jan 2013 22:30 NZST and most of the internet seems to have come to a crawl as Google Analytics seems to be running really slow. Stackoverflow, Firefox.com, reddit and google searches are slow. Most importantly for me, my production business website is running slow or not loading at all. No it's not just my connection I tested it on my phone with 3G as well. Sites without Google Analytics seemed to be running fine.
Here's a few screenshots of what happens
This is in the bottom left corner of the Firefox window. It will sit there for 20+ seconds like that. I'd like it to go away after 3 seconds if it can't connect.
This spinning green image is in the Firefox tab and just sits there making it look like the page is still loading for 20+ seconds. I'd like it to go away after 3 seconds if it can't connect.
Now it may not be Google Analytics, my country' international gateway may be running slow or something. But evidence strongly suggests it might be Google Analytics. Now even if it isn't Google Analytics then I'd still be interested in some methods to counter it if the service is completely down. So hypothetically lets assume there's a massive fire at the datacenter of Google Analytics and the fire suppression systems failed. Now Google Analytics goes completely offline for several days. No backup servers. No standby datacenters. Hypothetical scenario ok. Now my site still needs to run as I can't afford to have my site reliant on Google Analytics service being up. But the analytics functionality would be good to have as an added bonus if the service is actually running in a timely manner.
Ok so I'm throwing out some ideas here:
Is there's a timeout I can add to my script that will cancel the connection to Google Analytics and halt the request/download if it's taking too long? Then it would continue loading my site after 2 seconds.
Or better yet, perhaps it can just load my site completely, then send a request off to Google Analytics using Ajax after my site is completely finished loading? Why doesn't it do this by default?
Here's the code we have to work with which is currently inserted just before the closing </body> tag.
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-123456789-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
Now, what are some methods I could employ that would fix this hypothetical disaster scenario and give my website continuity while Google Analytics is down? I'm interested in either potential software or hardware solutions. Assume I have full access to a Linux VPS which my PHP/MySQL/HTML5 website is running on.
Also, what's the authoritative answer on this: some people say place the code before the closing </head> tag. Others say place it before the closing </body> tag. Which is the best way?
Many thanks
Solution Update
Ok I've found out what works with help from Jaspal. The solution is below.
<script type="text/javascript">
// Load Google Analytics after my site has completely loaded
// Then when Google Analytics request is made it won't show any visuals in the browser
setTimeout(loadGoogleAnalytics, 5000);
// Setup _gaq array as global so that the code in the ga.js file can access it
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-123456789-1']);
_gaq.push(['_trackPageview']);
/**
* Loads Google Analytics
*/
function loadGoogleAnalytics()
{
var srcUrl = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
$.ajax(
{
url: srcUrl,
cache: true,
dataType: "script",
success: function(data)
{
console.log('got the script');
},
error: function()
{
console.log('failed to get the script');
},
timeout: 5000
});
};
</script>
Basically why it works is because there is a setTimeout for 5 seconds. This gives my page enough time to load all the content, JS, CSS, images etc. Then after that it kicks off the $.ajax request and downloads ga.js and __utm.gif which is actually sending the data to Google Analytics. After that initial 5 seconds, basically all the browser visuals I mentioned earlier disappear and the Google Analytics request happens silently in the background with no loading visuals for the browser user. Then I tried blocking Google Analytics with the host file and I still don't get any browser visuals - perfect.
It should be noted that the timeout: 5000 property in the $.ajax request doesn't appear to do anything. Originally I was hoping it would abort the request if it couldn't get data for 5 seconds but there's a note in the API docs saying
In Firefox 3.0+ only, script and JSONP requests cannot be cancelled
by a timeout; the script will run even if it arrives after the timeout
period.
I'll leave it in there anyway just in case. From my testing if Google Analytics can't be reached (from observing the Net/Network panel in Firebug/Chrome) then it will abort the request after 21-23 seconds in Firefox and 16 seconds in Chrome. This may be some TCP timeout. I'm not worried about that anyway as it's timing out silently and the user will not notice as there's no loading visuals in the browser.
I have accepted Jaspal's answer below and awarded him the bounty as his solution was critical to solving this. However his solution still has loading visuals appearing in the browser. So I believe the solution posted here using the setTimeout (a slight modification on his original one) is the way to go and is tested to be working 100% for me.
Given where it's loaded, the rest of your site would load before the request to Google Analytics. Plus GA is loaded asynchronously, not halting the execution of any of your code, so I really don't see there being an issue.
Latest Approach :
We allow ga to load normally.
We store a reference to ga dom element in a global variable (gaClone).
We set a timeout of 30seconds. We also set another global variable (loadedGoogleAnalytics) and set it to 0 initially. When ga loads, we set this variable to 1. On the timeout expiry, we check whether ga was loaded or not. If not, we delete the dom element ga.
<script type="text/javascript">
var loadedGoogleAnalytics = 0;
var gaClone;
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-123456789-1']);
_gaq.push(['_trackPageview']);
_gaq.push(function() {
loadedGoogleAnalytics = 1;
//console.log('GA Actualy executed!');
});
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
gaClone = ga;
})();
setTimeout(function() {
//console.log('timeout fired');
if (loadedGoogleAnalytics != 1) {
gaClone.parentNode.removeChild(gaClone);
}
}, 30000);
</script>
[I have verified this approach with one of my actual GA accounts and i am able to see all the realtime tracking]
Previous Approach
[Note: Ga does not execute if we try to place it in (document).ready();]
[This solution does not work]
<script type="text/javascript">
$(document).ready(function() {
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-123456789-1']);
_gaq.push(['_trackPageview']);
srcUrl = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
$.ajax({
url: srcUrl,
cache: true,
dataType: "script",
success: function(data) {
//console.log('got the script');
},
error: function() {
//console.log('failed to get the script');
},
timeout: 30000
});
});
</script>
Hope this helps
You could host a copy of www.google-analytics.com/ga.js on your own server and load it from there. If you do go that route, I'd set up a cron job to periodically fetch ga.js to make sure you've got the most recent version.
Regarding tracking code placement: one of the main reasons for placing the tracking code earlier in the page (before </head>) has to do with visitors who leave the page quickly (possibly before the entire page has rendered). In that case, you're more likely to collect some data the sooner your tracking code is executed.
Trying to fix something that isn't broken
If you want to use Google analytics you are going to need to communicate with there server some how, period. There service, as pointed out by many of the other answers, run asynchronously meaning it doesn't prevent your site from running what so ever. The 'loading visuals' are there to show something is loading... there is very little you can do about this.
You have two options; put up with Google analytics or use some server side script to run analytics.
If the website is hanging it is because of something else.
Edit
Also not including GA immediately also reduces the accuracy of the stats; bounce rates in particular will not be correct.
According to EU Article 5(3) of the E-Privacy Directive (a.k.a 'The Cookie Laws'), web sites that target EU users have to gain opt-in consent from users before they set a cookie.
See ICO Guidance
I am trying to square this with Google Analytics on my web site.
I would imagine that Google Analytics (GA) can do a certain level of analytic data gathering without requiring the use of cookies.
However, I cannot find any info on this (on the Google sites/settings panels) about how to relay information about the 'state of consent' back to Google during a page request. So, my only option seems to be that I should not embed Google tag code at all if the user has not explicitly given consent. Which seems a bit drastic.
Letting my serverside script set a hasConsentedToCookies=FALSE flag in the JavaScript tags would allow me to instruct Google's services to run in a gracefully degraded fashion.
Is there a setting on Google Analytics to suppress use of cookies
for users that have not yet given consent?
If so, where can I find info on this?
EDIT (2019): The below answer predates GDPR and likely requires revision.
Google Analytics has a new set of APIs to assist with compliance with a cookie opt-out. Here's the documentation, and here's their help docs.
There has been some ambiguity as to whether the EU Cookie Regulations (as implemented in member countries) require that passive web analytics tracking requires opt-in mechanisms for compliance. If you're concerned one way or another, consult an attorney. Google is empowering you to make the decision as to how you want to proceed.
They'll leave implementation details to you, but, the idea is, once you've determined whether or not to track the user in Google Analytics, if the answer is to not track, you'd set the following property to true before Google Analytics runs:
window['ga-disable-UA-XXXXXX-Y'] = true;
Where UA-XXXXXX-Y is your account ID in Google Analytics
As the other posters have noted, Google Analytics relies on cookies. So, you're not able to do any kind of tracking without cookies. If you've determined that someone is not to be cookied for tracking, you'll need to implement something like this:
if(doNotCookie()){
window['ga-disable-UA-XXXXXX-Y'] = true;
}
Opt In
This does require a little bit of jujitsu for when you first load Google Analytics, since this property will need to be set before Google Analytics runs to prevent tracking from ever happening, which means, for an "opt in to tracking" approach, you'd probably need to implement a mechanism where, on first visit, Google Analytics is automatically disabled in the absence of an opt-in cookie (cookies that determine cookie preferences are explicitly allowed), and then, if an opt-in happens, re-runs Google Analytics. On subsequent pageviews, all would run smoothly.
Could look something like (pseudo-code):
if( hasOptedOut() || hasNotExpressedCookiePreferenceYet() ){ //functions you've defined elsewhere
window['ga-disable-UA-XXXXXX-Y'] = true;
}
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXXXX-Y']);
_gaq.push(['_trackPageview']);
function onOptIn(){ //have this run when/if they opt-in.
window['ga-disable-UA-XXXXXX-Y'] = false;
//...snip...
//set a cookie to express that the user has opted-in to tracking, for future pageviews
_gaq.push(['_trackPageview']); // now run the pageview that you 'missed'
}
Opt Out
With this approach, you'd allow the user to opt-out of tracking, which would mean you'd use a cookie to set the ga-disable-UA-XXXXXX-Y' property and a cookie to manage it in the future:
if( hasOptedOut() ){ // function you've defined elsewhere
window['ga-disable-UA-XXXXXX-Y'] = true;
}
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXXX-Y']);
_gaq.push(['_trackPageview']);
You can disable the use of cookies for Google Analytics by specifying the {'storage' : 'none'} option when creating the tracker instance.
See Google's guide on the subject for more details.
I often never ask users to opt out for google analytics, that is because i never set cookies and i never save their ip (and other personal data).
(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.google-analytics.com/analytics.js','ga');
ga('create', 'UA-98765432-1', 'www.example.com', {
'anonymizeIp': true
, 'storage': 'none'
, 'clientId': window.localStorage.getItem('ga_clientId')
});
ga(function(tracker) {
window.localStorage.setItem('ga_clientId', tracker.get('clientId'));
});
ga('send', 'pageview');
Also check out this code at Convert Google Analytics cookies to Local/Session Storage
This script will not set any cookies, but still track via google analytics. This will actually have the same effect on privacy as using cookies, because google still records the users IP-address.
That is where the anonymizeIp switch comes in. This tells google to only save an anonymized version of the IP-address. An anonymized IP-address is not considered personal data, so the users privacy will be respected.
AFAIK cookie law is all about privacy and does allow website to track their usage. I am not a lawyer or anything but in my opinion this script complies to the EU cookie law.
Check out this plunk to see it in action: http://plnkr.co/MwH6xwGK00u3CFOTzepK
As a quick note, the BBC (probably the most popular site in the UK) has taken an interesting approach to complying with cookies - they've displayed a banner to users telling them that cookies are set and provide a couple of links.
This one explains what cookies are. This one lets them manage their cookies, but most interestingly of all they supply a link to Google Analytics to allow users to opt-out of GA in its entirety. So, in summary, the BBC have taken the view that they can tell the user what cookies are set and then provide a link to Google to allow the user to opt out of all GA cookies. For me, that's a lot less hassle than you telling GA to opt-out for an address through JS.
Latest Google Analytics (gtag.js) has a "Consent mode" just for that (still in beta):
https://developers.google.com/gtagjs/devguide/consent
It looks like this:
gtag('consent', 'default', {
analytics_storage: 'denied',
ad_storage: 'denied'
});
Then you can update these settings at a later time in the case the user consents.
You can disable google analytics cookies by adding this code at the top of google analytics code (before line: var _gaq = _gaq || [];):
ga('create', 'UA-XXXXXX-XX', {'storage': 'none'});
ga(function(tracker) {
var clientId = tracker.get('clientId');
});
However some features of google analytics (for example real time stats) do not work properly after this modification. More about google analytics cookies: https://developers.google.com/analytics/devguides/collection/analyticsjs/domains?hl=en#disableCookies
I was facing the same problem.
Eventually, I got a solution in the line of Elmer's reply but playing safe regarding IPs, that is without using localStorage
// Create a fake ID instead of storing anything locally
function guidGenerator() {
var S4 = function() {
return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
};
return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
}
...
ga('create', 'UA-XXXXXX-Y', {
'storage': 'none',
'clientId': guidGenerator()
});
(-) Every page visited will count as a new visitor in Google Analytics, so I am losing quite a lot of functionalities there.
(+) But I can live with it and I believe I am safe regarding data privacy legislations.
Any feedback or improvement suggestion is more than welcome.
Common way to handle this so far is the method used by wolf-software's jquery plugin whereby it prevents the script from running until the user opts in. The ICO updated their guidelines last week, however, to say that it is acceptable to rely on 'implied consent' of the sort used on the BBC site. While I don't really think that's within the spirit of the law, it's what's deemed acceptable by those enforcing it. Given that most of the EU has yet to implement the directive, I'd say it's highly likely they'll follow the UK's lead.
There's an interesting article about the UK updates here:
http://www.redant.com/articles/eu-cookie-law-update-ico-adopts-softly-softly-approach/
EDIT: There is a Google Analytics setting for this with the Asynchronous GA snippet.
There isn't a Google Analytics setting for this, as you're suggesting, you would need to conditionally exclude the script for those that have not consented if you want to use the Google Analytics Javascript tracking script.
There are some solutions out there already that can be helpful instead of rolling your own.
Javascript: http://cookies.dev.wolf-software.com/demo/index.htm
Here is a solution that allows using Google Analytics basic features without cookies, by doing the tracking server side, this example is in PHP: http://techpad.co.uk/content.php?sid=205
For a less intrusive UX solution you can set implied consent for google analytical cookies by placing a link to: cookiestatement.eu (no javascript, no popups, no ads)
Sorry for being late to answer but I was looking for the same thing recently until I found out a way myself. It may not be the right way to do it but it works. (only works on site in question does not opt-out of GA completely).
I have tested for a few days to make sure.
The way I have managed to do it is using a PHP cookie. First start off with adding the analyticstracking.php include...
<?php include_once('analyticstracking.php'); ?>
and in analyticstracking.php add the following...
<?php
if($_COOKIE['consent_cookie']=="Y"){
?>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-********-*']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<?php
}
else{
//do nothing
}
?>
Before the user has consented to cookies Google Analytics won't work and once they have, the 'consent_cookie' will be saved and will allow GA to work but if the 'google' cookie is destroyed it will stop GA from working (Obviously).
Like I said it may not be the right way but I have tried and tested and it does. Hope this helps somebody.
Update 2022: Its not about Cookies anymore. Now you need a consent even for loading google fonts from outside the EU. This is because doing so the users IP (very private Information haha) will be send to the USA.
Im not a lawyer but this affects Adsense and Analytics as well. Here you will find a solution how to load Adsense and Analytics only if consent is given: https://stackoverflow.com/questions/70967060/loading-google-adsense-analytics-and-youtube-only-when-consent-is-given
Simply call setTimeout("analyticsladen()", 1); when consent is given:
The new Google Analytics 4 Code is:
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-####');
</script>
<script type="text/javascript">
function analyticsladen() {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://www.googletagmanager.com/gtag/js?id=G-####';
document.body.appendChild(script);
}
//setTimeout("analyticsladen()", 1);
</script>
Or you can use the old Google Universal Analytics Code. It will only work till June 2023 (says google):
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-####-#']);
_gaq.push (['_gat._anonymizeIp']);
_gaq.push(['_trackPageview']);
var analyticsladen = function(){
var ga = document.createElement('script');
ga.type = 'text/javascript';
ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s);
}
</script>
Funfact: Google ranks my page 4 steps higher scince im not using analytics at all anymore :D
There's a few steps to do in order to make GA work only after user accepts the cookie usage.
Disable cookies
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-XXXXXX-Y"></script>
-- <script>
-- window.dataLayer = window.dataLayer || [];
-- function gtag(){dataLayer.push(arguments);}
-- gtag('js', new Date());
-- gtag('config', 'UA-XXXXXX-Y');
-- </script>
At the point where GA is implemented, this needs to be updated by just importing the gtag.js script and removing the GA initialisation.
Enable GTag when user accepts cookies
GTag Opt In is a tool that enable and disable GA when user accepts/rejects cookies.
<script src="https://www.npmcdn.com/gtag-opt-in#2.0.0/dist/index.js"></script>
<script>
GTagOptIn.register('UA-XXXXXX-Y');
...
// On user opt in
GTagOptIn.optIn();
// On user opt out
GTagOptIn.optOut();
...
</script>
Library is loaded. GA tracking ID is registered. Later the optIn and optOut functions can bind to user actions' accept/reject.
You can read more about it on How To Implement Google Analytics With Opt In.
You can use something like Legal Monster - to block cookies if user didn't give consent for analytical cookies.
legal.js currently supports blocking (and enabling) of analytics and marketing cookies; more categories will be available in the future.
Here is more detailed guide on blocking cookies.
GA does not work without cookies, it needs it to 'identify s' the visitor if he/she visited your site before. So there is no setting in GA for this, GA just doesn't records the visitor if it cant create a cookie.
If the user is from the EU and has not opt-in then you should exclude the google-analytics script I think.
According to the Disqus comment code instructions, you're supposed to include their JavaScript as follows:
(function () {
var s = document.createElement('script');
s.async = true;
s.type = 'text/javascript';
s.src = 'http://' + disqus_shortname + '.disqus.com/count.js';
(document.getElementsByTagName('HEAD')[0] || document.getElementsByTagName('BODY')[0]).appendChild(s);
}());
The location of the JavaScript is based on a shortname that is specific to your site. Why does Disqus do that instead of using one global location for their JavaScript (e.g. cdn.disqus.com/count.js). If the JavaScript is the same for each site, it seems silly to require everyone to redownload the JavaScript for each Disqus-enabled domain they visit. If the JavaScript is different based on the shortname, why not just use a shortname variable that gets set before the global js is loaded?
Disqus is a fairly large and sophisticated company, so I'm assuming that this is a conscious and purposeful decision on their part. Why did they go this route?
Actually they are using a CDN to deliver count.js.
If <shortname> exists
http://<shortname>.disqus.com/count.js redirects to something like
http://mediacdn.disqus.com/1334018047/build/system/count.js.
To reduce traffic count.js(on the CDN) is delivered with an Expires-Header that allows caching it up to a month.
But imagine they need to change the code or block some sites or deliver special features to others, it would take up to a month until all clients get the changes. To reduce that timespan they probably use this redirect (which is cached for only up to 10 minutes), so code/feature changes will reach every client within 10 minutes.
It gives them a lot of flexibility and does not require the user to change the include code ever.
To optimize my site i have set up a static subdomain for content such as images, css and javascript. How do i stop the google analytics tracking cookie from being sent to my static subdomain, but still to both example.com and www.example.com?
Have already looked through some of the documentation with no luck
You can't have a cookie that gets sent to www.example.com and example.com but not othersubdomain.example.com.
You can in theory have a cookie that gets sent to example.com but not subdomain.example.com, but it doesn't work in IE.
This is why you should not use a no-www example.com address when you are planning on using subdomains with their own security context. It's best to have only one of www.example.com and example.com as the ‘proper’ URL anyway. So set up a redirect for example.com to go to www.example.com, and cookies won't be shared unless you deliberately set domain=.example.com on them.
If you're having issues with Google Analytics creating a cookie for every domain, including your subdomain ones. Here's my solution that I've posted elsewhere on the subject.
By golly I think I've found a temporary solution to the broken code supplied by Google.
If you go into GA and get the non-async code and choose:
One domain with multiple subdomains
Examples: apps.konoro.org
store.konoro.org
video.konoro.org
You'll see that it gives you a code sample with .konoro.org. Change that to www.konoro.org and all cookies will have: .www.konoro.org (with a dot in front of them).
Now if you go back to your Async code, there's only one difference apart from being Async. You need to put ['_setDomainName', 'www.konoro.org'], as the second option rather than after ['_trackPageview'].
For some reason, with this being the second option, it works fine.
My final code is:
var _gaq = _gaq || [];
_gaq.push(
['_setAccount', 'UA-XXXXXXX-1'],
['_setDomainName', 'www.konoro.org'],
['_trackPageview']
);
(function() {
var ga = document.createElement('script');
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
ga.setAttribute('async', 'true');
document.documentElement.firstChild.appendChild(ga);
})();
I've been travelling and developing for the past few weeks.
The site I'm developing was running well.
Then, the other day, i connected to a network and the page 'looked' fine, but it turns out the javascript wasn't running. I checked firebug, and there were no errors, as I was suspecting that maybe a script didn't load (I'm using the google api for jQuery and jQuery UI, as well as loading google maps api and fbconnect).
I would suspect that if the issue was with one of these pages not loading I would get an error, and yet there was nothing.
Thinking maybe i didn't connect properly or something, i reconnected to the network and even restarted my computer, as well as trying to run the local version. I got nothing.
The local version not running also hinted to me that it was the loading of an external javascript which caused the problem.
I let it pass as something strange with that one network. Unfortunately now I'm 100s of miles away.
Today my brother sent me an e-mail that the network he was on at the airport wouldn't load my page. Same issue. Everything is laid out properly, and part of the layout is set in Javascript, so clearly javascript is running.
he too got no errors. Of course, he got on his plane, and now he is no longer at the airport. Now the site works on his computer (and i haven't changed anything).
How on earth would you go about figuring out what happened in this situation? That is two of maybe 12 or so networks. But I have no idea how i would find a network that doesn't work (and living in a small town, it could be difficult for me to find a network that doesn't work).
Any ideas?
The site is still in Dev, so I'd rather not post a link just yet (but could in a few days).
What I can see not working is the javascript functions which are called on load, and on click. So i do think it is a javascript issue, but no errors.
This wouldn't be as HUGE an issue if I could find and sit on one of these networks, but I can't. So what would you do?
EDIT ----------------------------------------------------------
the first function(s - their linked) that doesn't get called is below.
I've cut the code of at the .ajax call as the call wasn't being made.
function getResultsFromForm(){
jQuery('form#filterList input.button').hide();
var searchAddress=jQuery('form#filterList input#searchTxt').val();
if(searchAddress=='' || searchAddress=='<?php echo $searchLocation; ?>'){
mapShow(20, -40, 0, 'areaMap', 2);
jQuery('form#filterList input.button').show();
return;
}
if (GBrowserIsCompatible()) {
var geo = new GClientGeocoder();
geo.setBaseCountryCode(cl.address.country);
geo.getLocations(searchAddress, function (result)
{
if(!result.Placemark && searchAddress!='<?php echo $searchLocation; ?>'){
jQuery('span#addressNotFound').text('<?php echo $addressNotFound; ?>').slideDown('slow');
jQuery('form#filterList input.button').show();
} else {
jQuery('span#addressNotFound').slideUp('slow').empty();
jQuery('span#headerLocal').text(searchAddress);
var date = new Date();
date.setTime(date.getTime() + (8 * 24 * 60 * 60 * 1000));
jQuery.cookie('address', searchAddress, { expires: date});
var accuracy= result.Placemark[0].AddressDetails.Accuracy;
var lat = result.Placemark[0].Point.coordinates[1];
var long = result.Placemark[0].Point.coordinates[0];
lat=parseFloat(lat);
long=parseFloat(long);
var getTab=jQuery('div#tabs div#active').attr('class');
jQuery('div#tabs').show();
loadForecast(lat, long, getTab, 'true', 0);
var zoom=zoomLevel();
mapShow(lat, long, accuracy, 'areaMap', zoom );
}
});
}
}
function zoomLevel(){
var zoomarray= new Array();
zoomarray=jQuery('span.viewDist').attr('id');
zoomarray=zoomarray.split("-");
var zoom=zoomarray[1];
if(zoom==''){
zoom=5;
}
zoom=parseFloat(zoom);
return(zoom);
}
function loadForecast(lat, long, type, loadForecast, page){
jQuery('div#holdForecast').empty();
var date = new Date();
var d = date.getDate();
var day = (d < 10) ? '0' + d : d;
var m = date.getMonth() + 1;
var month = (m < 10) ? '0' + m : m;
var year='2009';
toDate=year+'-'+month+'-'+day;
var genre=jQuery('span.genreblock span#updateGenre').html();
var numDays='';
var numResults='';
var range=jQuery('span.viewDist').attr('id');
var dateRange = jQuery('.updateDate').attr('id');
jQuery('div#holdShows ul.showList').html('<li class="show"><div class="showData"><center><img src="../hwImages/loading.gif"/></center></div></li>');
jQuery('div#holdShows ul.'+type+'List').livequery(function(){
jQuery.ajax({
type: "GET",
url: "processes/formatShows.php",
data: "output=&genre="+genre+"&numResults="+numResults+"&date="+toDate+"&dateRange="+dateRange+"&range="+range+"&lat="+lat+"&long="+long+'&page='+page,
success: function(response){
EDIT 2 -----------------------------------------------------------------------------
Please keep in mind that the problem is not that I can't load the site, the site works fine on most connections, but there are times when the site doesn't work, and no errors are thrown, and nothing changes. My brother couldn't run it earlier today while I had no problems, so it was something to do with his location/network. HOWEVER, the page loads, he had a connection, it was his first time visiting the site, so nothing could have been cashed. Same with when I had the issue a few days before. I didn't change anything, and I got to a different network and everything worked fine.
Two things: first -- get the javascript local to your site when developing. Loading it from elsewhere to take advantage of caching is an optimization that I'd leave to the end. I'd also only load it from highly available remote sites, like Google, to minimize problems. Second, make your site at least minimally usable without javascript enabled. Use form postbacks that get replaced with Ajax functionality from javascript that runs when the page is loaded, for example. You might not be able to get everything, but I've found that I can make most things work without javascript in at least a workable, if not elegant fashion.
I realize this doesn't solve your immediate problem, but I think it would help your site to remain available in the face of situations like this.
Turns out the problem with this was in assuming that google map could find any lat/long within north america reliably via ip address.
I add a if(!google.loader.ClientLocation) function for the instances where google cannot find the location via ip.
The strangest bit was that I was hitting this error in an office in downtown Palo Alto which I thought would have been heavily mapped by the google geocoder.
If some of the JS is being hosted by a different server (eg: if you are including something like jQuery from the jQuery site instead of hosting a copy of it yourself) then maybe one of these sites is down temporarily.
You could try use something like "Live HTTP Headers" (available at the Mozilla Addons site) to watch HTTP headers in real-time, which can be really useful when doing web development. You should be able to determine very quickly if all your JS is in fact loading correctly or not.
You could also use something like Ethereal or Wireshark, but that is probably a little heavy-handed when all you need is to see the request/response headers. Using an Addon is far less hassle.
A few things:
1.) where you include your scripts... make sure you have a separate closing tag! DO NOT self close them.
<script src="..."/><!--self-closing will fail, -->
<script src="..."></script><!--this will work -->
2.) is there a reason why you are using jQuery() rather than $() ?
3.) does your SERVER specify a DOCTYPE that your local environment didn't?
4.) what browser are you testing in? in particular are you testing in IE, if so does it work in Firefox?
5.) can you post some of the generated code if you can't supply a URL?
Once you're sure that all the scripts are loading as expected in the dev environment you could try either removing them one-by-one from the page and see which one recreates the issue you were having - then that's the script that wasn't loading.
Firebug has a Net Tab which does something very similar to what Live HTTP Headers does, even tracking the timings of the load and any ajax requests.
I almost always recommend Firefox plugin, "Firebug" for this.
Firstly, you can inspect the scripts to check that they have loaded, which will rule out the "it didn't load from a remote source" problem.
Secondly, it will display errors that occur in the JavaScript console, which may point out something that appeared to be silently previously.
Lastly, keep an eye out for cross-site-scripting problems when using JavaScript from another domain.