Here's a full copy of my HTML page, so you can see what I'm talking about:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Test Page</title>
<meta name="robots" content="noindex, nofollow">
<script type="text/javascript">
_atrk_opts = { atrk_acct:"/123456", domain:"example.com",dynamic: true};
(function() { var as = document.createElement('script'); as.type = 'text/javascript'; as.async = true; as.src = "https://123.cloudfront.net/sample.js"; var s = document.getElementsByTagName('script')[0];s.parentNode.insertBefore(as, s); })();
</script>
<script type="text/javascript">
_atrk_opts = { atrk_acct:"/tester", domain:"other.com",dynamic: true};
(function() { var as = document.createElement('script'); as.type = 'text/javascript'; as.async = true; as.src = "https://123.cloudfront.net/sample.js"; var s = document.getElementsByTagName('script')[0];s.parentNode.insertBefore(as, s); })();
</script>
<script>
(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','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-91071000-1', 'auto');
ga('send', 'pageview');
</script>
</head>
<body>
<script>
window.location = "http://test.com";
</script>
</body>
</html>
I have 3 scripts in the header that I need to fully run before the Javascript redirect in the body is run.
All of the scripts load pixels and are used for analytics tracking. Basically the problem I'm having is that only a percentage of visitors are being tracked because the redirect in the body is running before the snippets in the header are completed.
I would prefer a solution that guarantees the javascript is run before actually redirecting a visitor - I'm away that I could setup a timer to run my redirect after X seconds, but there's no way to know if the other scripts are done (although they should be very quick).
Any advice or solutions would be great. Thanks!
_atrk_optswill always be the value of the second declaration. So just add one script tag just after a script that sets _atrk_opts to the second value. replacing the first two scripts with.<script>_atrk_opts = { atrk_acct:"/tester", domain:"other.com",dynamic: true};</script><script src ="https://123.cloudfront.net/sample.js"></script>Then remove the last 4 lines in the anon function and add the<script src='https://www.google-analytics.com/analytics.js'>after 3rd script. then use onload to run your redirect