动态地将脚本注入<head>?

all*_*tta 3 javascript reactjs

在 React 中,我试图在加载特定组件时动态添加<script>a 。<head>我之前曾将此代码用于类似的事情(使用更简单的脚本):

componentWillMount() {
    var script= document.createElement('script');
    script.src = "SOME_URL";
    document.body.appendChild(script);
}
Run Code Online (Sandbox Code Playgroud)

但是我现在尝试注入 head 的代码包含缩小的 js (它是 Google Analytics 内容实验代码),如下所示:

<!-- 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 -->
Run Code Online (Sandbox Code Playgroud)

我如何动态地将其注入<head>

更新:我最终使用了他们的客户端解决方案

Pav*_*o D 6

如果你想添加一个带有 src 属性的脚本标签到head你应该使用

var script= document.createElement('script');
script.src = "SOME_URL";
document.head.appendChild(script); 
Run Code Online (Sandbox Code Playgroud)

注释文档。,不是身体

如果你想添加一个包含一些脚本的脚本标签,请使用

var script= document.createElement('script');
script.text = "CODE";
document.head.appendChild(script);
Run Code Online (Sandbox Code Playgroud)

如果您只需要在页面上运行此代码,您可以使用eval("CODE"); where code是您的 js 代码,无需脚本标签

也许这个工具可以帮助逃脱