2

In React I am trying to dynamically add a <script> to <head> when a specific component loads. I have previously used this code to similar things (with much simpler scripts):

componentWillMount() {
    var script= document.createElement('script');
    script.src = "SOME_URL";
    document.body.appendChild(script);
}

But the code I am now trying to inject into head contains minified js (it is Google Analytics Content Experiment code), like this:

<!-- Google Analytics Content Experiment code -->
<script>function utmx_section(){}function utmx(){}(function(){var
k='XXXXXXXXX-Y',d=document,l=d.location,c=d.cookie;
if(l.search.indexOf('utm_expid='+k)>0)return;
function f(n){if(c){var i=c.indexOf(n+'=');if(i>-1){var j=c.
indexOf(';',i);return escape(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/ga_exp.js?'+'utmxkey='+k+
'&utmx='+(x?x:'')+'&utmxx='+(xx?xx:'')+'&utmxtime='+new Date().
valueOf()+(h?'&utmxhash='+escape(h.substr(1)):'')+
'" type="text/javascript" charset="utf-8"><\/sc'+'ript>')})();
</script><script>utmx('url','A/B');</script>
<!-- End of Google Analytics Content Experiment code -->

How can I dynamically inject that into <head>?

Update: I ended up using their client-side solution.

allegutta
  • 5,626
  • 10
  • 38
  • 56
  • Possible duplicate of http://stackoverflow.com/questions/3267485/how-to-append-a-line-of-javascript-rather-than-an-exteral-js-file – helb Feb 27 '17 at 16:06
  • If I can use appendChild, how could I put the whole minified js into one string (since it contains both `"` and `'`)? – allegutta Feb 27 '17 at 16:20
  • 3
    Do you *really* need to inject that script dynamically? Why not just include it in your HTML template? – Aaron Beall Feb 27 '17 at 16:40
  • When wrapping the whole minified js into `"` (using `\"` on the `"` that is inside the minified js), I get this error: `SyntaxError: Unterminated string constant`, any idea why? – allegutta Feb 27 '17 at 16:42
  • @Aaron Good question. If I place the script directly in the `` (in `index.html`), it will redirect 50% of the users to the B-test directly from `/`. But I only want to redirect them when they are entering `/this` – allegutta Feb 27 '17 at 16:47
  • @allegutta Seems that you need to escape `//` as well (so it becomes `\/\/`), since JS thinks it's a comment. Sorry about that. Working codepen example: http://codepen.io/helb/pen/peJOoN – helb Feb 27 '17 at 17:02

1 Answers1

6

if you want to add a script tag with src attribute to head you should use

var script= document.createElement('script'); script.src = "SOME_URL"; document.head.appendChild(script);

note document.head, not body

if you want to add a script tag with some script inside, use

var script= document.createElement('script'); script.text = "CODE"; document.head.appendChild(script);

if you just need to run this code on your page you can use eval("CODE"); where code is your js code without script tags

maybe this tool can help with escaping

Pavlo D
  • 346
  • 2
  • 8
  • The escape tool helped. In Chrome I was unable to inject script until it was fully escaped, so thanks for mentioning it! – Fütemire Mar 29 '18 at 16:34
  • If you want to wait for the script to load before taking action, see [Waiting for dynamically loaded script](https://stackoverflow.com/questions/7308908/waiting-for-dynamically-loaded-script). – ggorlen May 29 '21 at 15:26
  • Thanks, bro <3. It's working perfectly – Spandan Joshi Jan 04 '22 at 17:08