Google Content Experiments and Analytics on same page: Adding scripts in correct order

491 Views Asked by At

I'm trying to run a Content Experiment, so the basic structure of the <head> should look like the following:

<head>
    <!-- Content experiments code (CE) -->
        ***
    <!-- End CE code -->

    *** Standard <head> code: title, meta, CSS, JS, etc. ***

    <!-- Google Analytics code -->
        ***
    <!-- End GA code -->
</head>

But, here's the issue:

Amongst the various JS being loaded is Google Tag Manager:

<script async="" src="//www.googletagmanager.com/gtm.js?id=GTM-***"></script>

This file dynamically loads another script:

<script type="text/javascript" async="" src="//www.googleadservices.com/pagead/conversion_async.js"></script>

Unfortunately for me, it does this by inserting it before the first <script> tag using the following method:

...
getElementsByTagName('script')[0].insertBefore(newScriptObject);
...

Incase it isn't obvious why this is a problem, the Content Experiment script should be the first element in the <head>. But, because this script is inserted before the first script element, it isn't.

To compound this, other scripts (also outside of my control) are also loaded by this method. So, even though in the document the Content Experiment code is first, after the JS executes and updates the DOM, there are numerous script elements placed before it.

So, does it matter?

Am I right in thinking that this doesn't actually matter? As on page load, the first script element will be the one loading the content experiment script (which is correct) as the other files haven't been dynamically inserted yet.

Will the CE script be loaded and run before the rest of the scripts are loaded?

Apologies for a slightly long winded way of asking a quite straight-forward question, but, well, yeah.

Thanks for the help,

Tom

1

There are 1 best solutions below

0
On

This is a standard practice on the net and totally fine. Good digging in and debugging though! Content Experiments just wants you to load the script close to the top of your head so that they can redirect people away from the control url with as little impact to performance as possible.

Edit: AND so that they don't get a lot of support tickets when people accidently include CE AFTER google analytics.