Link to home
Start Free TrialLog in
Avatar of AWSHelpdesk
AWSHelpdesk

asked on

Dynamically add script to head of page

I need to dynamically add some Google Optimizer code into the head of my page.

I am using the following JS and it seems to add ti because I have an alert in the js file and it is being called, yet google optimzer can't seem to see it and I can't see the reference to the file in the page source?

var scriptStart = document.createElement( 'script' );
scriptStart.type = 'text/javascript';
scriptStart.src ="/include/JS/semAB-top.js";
$(document.head).append(scriptStart);
Avatar of ezkl
ezkl

The first thing that I would do is check the path to the source file of the JS. Depending on your hosting environment, the path may need to be adjusted so that the file can be accessed.
ASKER CERTIFIED SOLUTION
Avatar of leakim971
leakim971
Flag of Guadeloupe image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of AWSHelpdesk

ASKER

Ah ha, maybe!

This is what is in the script
function utmx_section(){}
function utmx(){}
(function(){
		  var k='xxxxxx',d=document,l=d.location,c=d.cookie;
		  function f(n){
			if(c){var i=c.indexOf(n+'=');
			if(i>-1){var j=c.indexOf(';',i);
			return c.substring(i+n.length+1,j<0?c.length:j)}}}var x=f('__utmx'),xx=f('__utmxx'),h=l.hash;
			d.write('<sc'+'ript src="'+'http'+(l.protocol=='https:'?'s://ssl':'://www')+'.google-analytics.com'+'/siteopt.js?v=1&utmxkey='+k+'&utmx='+(x?x:'')+'&utmxx='+(xx?xx:'')+'&utmxtime='
+new Date().valueOf()+(h?'&utmxhash='+escape(h.substr(1)):'')+'" type="text/javascript" charset="utf-8"></script>')
			});

utmx("url",'A/B');

Open in new window

BTW there are no js errors on the page
Line 9, we have :

document.write('<script src= bla bla bla type="text/javascript" charset="utf-8"></script>');

So we've a script tag inside a script tag. It can't work.
<script language="javascript"> <-- your
   <script language="javascript"></script> <---- the google one
</script>

Open in new window

This is the code that Google Optimizer gave me to use and if I put it direclty into the code in <script> tags it does work it is jsut when I try and call it from an external js file that Google is not seeing it
I know.
This code run at page load and create a code to run in a script tag. If you put this code inside an other script tag it can't be run.
Why would Google give you this code to add then?
The code run fine if you don't put it in anothor script tag :

Replace :

<script language="javascript"> <-- your
   <script language="javascript"></script> <---- the google one
</script>

By :


<script language="javascript"> <-- your
</script>
<script language="javascript"> </script> <---- the google one

Open in new window