I've currently got 4 different javascripts for ad tracking. They look something like this:
<script type='text/javascript'> var TrackerKey = 'keyabc123'; var url = 'http://website.com/jscode.js'; var script = document.createElement('script'); script.setAttribute('src', url); script.setAttribute('type', 'text/javascript'); document.body.appendChild(script);</script>
I want to combine all 4 and simply have the tracker key swap out based off the sub domain name they're on.
Thus far I've been able to work out that I would use the window.location.hostname to find what the domain is. And I would probably use a switch statement or if/else approach.
I'm not experienced enough though to know how to pass on the information of what the domain is as a variable to the switch statement, and then use that to update the tracker key variable.
I assume it might look something like the following...
<script type='text/javascript'>
var domain = window.location.hostname;
var TrackerKey;
switch (???) {
case 0:
sub.domain1.com = "keyabc123";
break;
case 1:
sub.domain2.com = "keydef456";
break;
case 2:
sub.domain3.com = "keyghi789";
break;
case 3:
sub.domain4.com = "keyjkl012";
break;
}
var url = 'http://website.com/jscode.js'; var script = document.createElement('script'); script.setAttribute('src', url); script.setAttribute('type', 'text/javascript'); document.body.appendChild(script);</script>
Am I remotely on the right path?
Apologies, this is my first stab at something beyond the very basics.
You're close:
var domain = window.location.hostname;
var TrackerKey;
switch (domain) {
case "sub.domain1.com":
TrackerKey = "keyabc123";
break;
case "sub.domain2.com":
TrackerKey = "keydef456";
break;
case "sub.domain3.com":
TrackerKey = "keyghi789";
break;
case "sub.domain4.com":
TrackerKey = "keyjkl012";
break;
}
Also by convention in Javascript, variable and function names are camel case starting with a lowercase character, and Classes are camelCase starting with a capital character.
var subdomain = window.location.hostname.match(/(http:\/\/)?(([^.]+)\.)?domain\.com/)[3]
Change 'domain' above to your domain and then use
var TrackerKey;
switch(subdomain) {
case 'abc': //abc.domain.com
TrackerKey = 'abc123';
break;
}
And then do your usual script insert.
Regex ref: Regex to extract subdomain from URL?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With