How to write a Google Content Experiment that disables a stylesheet?

675 views Asked by At

I am currently trying to setup a Client Side Experiment without Redirects as opposed to the default Content Experiment A/B testing. All I want to do is for half my visitors disable one of two existing stylesheets on a page.

To me it doesn't make sense to do this the default A/B way because then I would have to setup a second page with the stylesheet disabled for every page on my site.

There is also Running a Server-side Experiment but to me that is too heavy handed for something I think should be somewhat simple.

I have the js all setup, I just need to be able to tell the page that when there is a given variation disable the stylesheet or don't render the stylesheet before the DOM loads.

One thing I considered is, given a certain variation, redirect to the same page but append a url query parameter like &stylesheet_disabled=true then I would simply not render the stylesheet on the server side but when I briefly looked at that I ran into a redirect loop but perhaps someone has a better way to write the js.

Any help greatly appreciated.

2

There are 2 answers

1
rodyhaddad On BEST ANSWER

You could do something like this:

<head>
  ...
  <script>
    if (cxApi.chooseVariation() != 1) { // not in the experiment
      document.write('<link href="... />'); // add the stylesheet
    }
  </script>
  ...

Only use document.write while the page is still being loaded.

This is all client-side, so no need for redirects and extra server work.

0
jcroll On

Here is how I did it:

<head>
    <script src="//www.google-analytics.com/cx/api.js?experiment=EXPERIMENT_ID"></script>
    <script>
        // Ask Google Analytics which variation to show the visitor.
        var chosenVariation = cxApi.chooseVariation();
        function redirectVariation($variation) {
            var url = window.location.href;
            if ($variation === 1) {
                var queryString = document.location.search;
                if (queryString.indexOf("stylesheet_disabled=true") == -1) {
                    if (Boolean(queryString)) {
                        url += "&stylesheet_disabled=true";
                    } else {
                        url += "?stylesheet_disabled=true";
                    }
                    window.location.href = url;
                }
            }
        }
        redirectVariation(chosenVariation);
    </script>

This is only setup for one different variation but could easily be modified for more. Then you just have your application on the server side detect the presence of the querystring parameter and execute whatever logic you like, in my case not displaying a stylesheet.

Theoretically this could be used to do any kind of server side logic with GA Content Experiment Client Side Redirects. Hopefully this helps someone else.