Run multiple simultaneous tests with Google Content Experiments API - google-analytics

I'm trying to use Google Content Experiments API to run several A/B tests simultaneously in the same page (similar to a multivariate test).
I've tried just putting all the recommended code for each test one after another, like this:
<script src="//www.google-analytics.com/cx/api.js?experiment=8RsNt4b7T0aE8RC2s9R3IA">/script>
<script>
var chosenVariation = cxApi.chooseVariation();
var pageVariations = [
function() {},
function() {
$(".block1").hide();
},
];
$(document).ready(
pageVariations[chosenVariation]
);
</script>
<script src="//www.google-analytics.com/cx/api.js?experiment=T3m-MvunQ6wY6StbPDqzTg"></script>
<script>
var chosenVariation = cxApi.chooseVariation();
var pageVariations = [
function() {},
function() {
$(".block2").hide();
}
];
$(document).ready(
pageVariations[chosenVariation]
);
</script>
This is working but not correctly: All the tests get visitors according to the Google Analytics dashboard, but the last one to appear in the code gets a lot of them (probably all the real visitors to the page) and the others only a fraction of the total visitors. I guess this could be related to loading the "cx/api.js" script several times.
After searching a lot, I've found two related issues with possible solutions, but I don't fully understand how they work:
https://productforums.google.com/forum/#!topic/analytics/R3u8yagLr48
How can you choose variations for several content experiments?
(I've tried to comment on this answer instead of creating a new question, but I don't have enough reputation in StackOverflow to comment).
I guess the solution could be some variation of the code provided in the answer of the last link, but I don't know much Javascript and therefore don't know what I should change exactly to achieve what I want (multiple experiments concurrently in the same page).
Thanks a lot for your help! ;)

Related

Cannot create reports for custom dimensions/metrics GA4

I have implemented a feedback star rating on my website at the bottom of each page. They can select one to five stars and optionally send free-form comments. I have implemented gtag.js to send the star rating integer and comments to my GA4 dashboard. Code snippet is below; I have omitted the JavaScript which allows the user to set the variables, but this is working.
<script async src="https://www.googletagmanager.com/gtag/js?id=MEASUREMENT_ID"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'MEASUREMENT_ID', {
'custom_map': {
'rating_dimension': 'rating_key',
'comments_dimension': 'comments_key'
},
'rating_key': 'this.value',
'comments_key': 'commentsValue',
});
</script>
gtag('event', 'rating_event', {'rating_key': this.value });
gtag('event', 'comments_event', {'comments_key': commentValue });
I went under Configure>Custom definitions and added the dimensions under the Event scope.
The data is being sent as an event, because this is something the user can optionally do on a page. I have verified that the data is sent to GA, I have the Google Chrome GA Debugger, and can see that it is arriving in the Realtime report under Events.
I would like to build a report which shows the page title/URL, the number of views, the length of time spent, along with its average star rating and any comments. I would like to have some adjustable controls so that I can configure this to be shown for a specified length of time. For example, if the page is modified, I can see the average rating before and after the change. Unfortunately, I am not able to build even the most rudimentary view of this data in the new GA web interface. I tried to modify various existing reports to include my custom dimensions, but they don't offer this option. I went under Explore and tried to add a Freeform report, but I can't get the data to show up there either, it only counts the number of times the event has occurred, which is not what I care about at all.
I have gone to a lot of effort to send the data to GA and had expected to be able to access the data and build a basic report.
Is it that you are unable to add custom dimensions and metrics to the free form exploration? Or when you want to add dimensions or metrics, they don't even show up in the custom section?
Normally you have to wait more or less (some say up to) 24 hours before being able to use custom definitions (metrics and dimensions) in any report.
this might not be your case, but I found your post looking for an answer to my problem, which is the custom metrics and dimensions are there, I am just unable to add them to the report, it looks like a bug, I click the + button, check the custom dimensions and nothing happens.

Recaptcha V3 assets cause Pagespeed issues - how to defer

We're currently using Google Recaptcha V3 across the public-facing portions of our site - while doing Pagespeed Insights performance testing (Mobile), Google themselves is reporting unused/undeferred CSS as a problem on their own Recaptcha css file:
Full resource address is:
https://www.gstatic.com/recaptcha/releases/[...]/styles__ltr.css (so it is clearly coming from a subsequent Google Recaptcha script request)
We are including the original Google recaptcha script with the 'defer' attribute set - not sure what else we can do to cause this css to be deferred such that Pagespeed does not complain about it. Can't find any documentation on the Google Recaptcha site itself to help with this issue.
Does anyone know how to defer this CSS to improve page load time? Not sure if this is somehow a Mobile specific issue, as Pagespeed doesn't report it at all on Desktop.
Firstly, bear in mind that 'remove unused CSS' is more of a guidance point (provided it isn't render blocking), it is indicating that it is wasted bytes (which it actually isn't if recaptcha triggers, as it then needs that CSS to render the image 'are you human check' etc.)
Although I can't give you an ideal answer as it is code you have no control over, I can give you two ways to test it's impact / whether it is actually a problem and a 'hack' to get around the load order.
Test using applied throttling
Simulated throttling can cause unexpect behaviour sometimes, which is what the Page Speed Insights website uses.
If you use the browser audit (which uses the same engine - Lighthouse) to run the tests you have an option to change the throttling from simulated to applied.
Although your score will change (applied throttling is less forgiving than simulated throttling), you get a much more realistic order of events as the latency and slowdown is 'real' vs making best guesses based on loading the page at full speed and applying formula's to guess load times.
Open Dev Tools in Chrome (F12) -> Audits -> Throttling -> set to Applied Slow 4G, 4x CPU Slowdown. -> Run Audits.
See if the problem persists when using this way of assessing page speed.
If it does, a workaround / test for real world performance is as follows:-
Force the script to load after an amount of time (the hacky way!)
This is not an ideal solution but it is good for testing and as a last resort if it does actually slow down your website key load times.
Insert the script dynamically after 5 seconds.
(please note the below code is untested and is likely to not work, it is for illustration only to point you in the right direction. It is highly probable that you don't need the script.onload section and can include that normally)
setTimeout(function(){
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.onload = function() {
grecaptcha.ready(function() {
grecaptcha.execute('_reCAPTCHA_site_key_', {action: 'homepage'}).then(function(token) {
...
});
});
}
script.src = "https://www.google.com/recaptcha/api.js?render=_reCAPTCHA_site_key";
head.appendChild(script);
}, 5000);
We can use IntersectionObserver to defer Recaptcha script.
var io = new IntersectionObserver(
entries => {
console.log(entries[0]);
if (entries[0].isIntersecting) {
var recaptchaScript = document.createElement('script');
recaptchaScript.src = 'https://www.google.com/recaptcha/api.js?hl=en';
recaptchaScript.defer = true;
document.body.appendChild(recaptchaScript);
}
},
{
root: document.querySelector('.page-wrapper'),
rootMargin: "0px",
threshold: 1.0,
}
);
io.observe(initForm);
We can load the reCaptcha v3 script once after an initial scroll on load:
var fired = false;
window.addEventListener('scroll', function () {
let scroll = window.scrollY;
if (scroll > 0 && fired === false) {
var recaptchaScript = document.createElement('script');
recaptchaScript.src = 'https://www.google.com/recaptcha/api.js?render=Your_SITE_KEY';
recaptchaScript.defer = true;
document.body.appendChild(recaptchaScript);
fired = true;
// console.log('On scroll fired');
}
}, true);
Code Example:
https://codepen.io/iamrobert/pen/NWazNpd
Page Speed Insight Score

casperjs and a/b testing

i have a signup.js test that automates signing up for my web app (obviously). we're currently a/b testing a new flow that takes you to a different page ('.com/signupa' vs '.com/signupb') and i'm wondering what the best way to reflect this in my test.
options:
use evaluateOrDie and make it die at .com/signupb (this seems dumb)
flesh out test for .com/signupb and make it go that route if it hits that test (is this possible?) something like..
casper.waitForResource("classic.png",
function success() {
this.echo('on the old signup flow ');
<continue with regular signup test>
},
function fail() {
this.test.assertExists("classic.png");
<do something else>
});
any other ideas greatly appreciated!
My preference would be to hide some information in each of your pages, so you can cleanly switch on them. E.g.
<span id="version1"></span>
vs.
<span id="version2"></span>
Then, after submitting the form:
casper.then(function(){
if (this.exists('#version2')) {
testNewSite(this);
} else {
testOldSite(this);
}
});
But detecting on something you already know is only in one of the pages, like the "classic.png" you show in your question, is also fine. (It just feels a little more brittle: the web development team can break your tests by renaming that image, or putting an image with that name in the new version, etc., etc.)

Making autocomplete search faster in asp.net

I have implemented an auto-complete search on my website using ajax autocomplete control.It uses web service which returns results from database.
I have a stored procedure which searches for all text values in all columns of all tables for this purpose.
The problem here is results taking long to show up in autcomplete control.
I have also applied indexing on the most frequently searched table columns, but that to didn't help much. Can this be because of the load on the server, since the server is not a dedicated one. If not how can I fetch the results faster?
You can always optimise the queries to load data faster and use server side caching to cache the data.
Also on UI I would recommend you to use jQuery autocomplete plugin
<script>
$(function() {
var availableTags = [
"ActionScript",
"AppleScript"
];
$( "#tags" ).autocomplete({
source: availableTags
});
});
</script>

Run Javascript on the body of a Gmail message

I want to display LaTeX math in the gmail messages that I receive, so that for example $\mathbb P^2$ would show as a nice formula. Now, there are several Javascripts available (for example, this one, or MathJax which would do the job, I just need to call them at the right time to manipulate the gmail message.
I know that this is possible to do in "basic HTML" and "print" views. Is it possible to do in the standard Gmail view? I tried to insert a call to the javascript right before the "canvas_frame" iframe, but that did not work.
My suspicion is that manipulating a Gmail message by any Javascript would be a major security flaw (think of all the malicious links one could insert) and that Google does everything to prevent this. And so the answer to my question is probably 'no'. Am I right in this?
Of course, it would be very easy for Google to implement viewing of LaTeX and MathML math simply by using MathJax on their servers. I made the corresponding Gmail Lab request, but no answer, and no interest from Google apparently.
So, again: is this possible to do without Google's cooperation, on the client side?
I think one of the better ways to do this might be to embed images using the Google Charts API.
<img src="http://chart.apis.google.com/chart?cht=tx&chl=x=\frac{-b%20\pm%20\sqrt{b^2-4ac}}{2a}">
To Learn more: https://developers.google.com/chart/image/ [note, the API has been officially deprecated, but will work until April 2015]
If you really must use LaTeX and some js library, I think one way you could accomplish this is by injecting a script tag into the iframe.
I hope this is a good starting point.
Example:
// ==UserScript==
// #name Test Gmail Alterations
// #version 1
// #author Justen
// #description Test Alter Email
// #include https://mail.google.com/mail/*
// #include http://mail.google.com/mail/*
// #license GPL version 3 or any later version; http://www.gnu.org/copyleft/gpl.html
// ==/UserScript==
(function GmailIframeInject() {
GM_log('Starting GMail iFrame Injection');
var GmailCode = function() {
// Your code here;
// The ':pd' (div id) changes, so you might have to do some extra work
var mail = document.getElementById(':pd');
mail.innerHTML = '<h1>Hello, World!</h1>';
};
var iframe = document.getElementById('canvas_frame');
var doc = null;
if( iframe ) {
GM_log('Got iFrame');
doc = iframe.contentDocument;
} else {
GM_log('ERROR: Could not get iframe with id canvas_frame');
return
}
if( doc ) {
GM_log('Injecting GmailCode');
var code = "(" + GmailCode + ")();"
doc.body.appendChild(doc.createElement('script')).innerHTML=code;
} else {
GM_log('ERROR: Could not get iframe content document');
return;
}
})();
Well, there are already greasemonkey scripts that do things to GMail as far as i know (like this one). Is this a possible security hole? Of course, anything you'd do with executable code has that risk. Google seems to move a glacial speeds on things they're not interested in. They really do seem to function based on internal championing of ideas, so best way forward is to go find sympathetic googlers, if you want them to include something into GMail. Otherwise stick to Greasemonkey, at least you'll have an easy install path for other people who'd like to see the same functionality.

Resources