在 React 中,我尝试动态添加 <script>
至<head>
当特定组件加载时。我之前曾使用此代码来完成类似的事情(使用更简单的脚本):
componentWillMount() {
var script= document.createElement('script');
script.src = "SOME_URL";
document.body.appendChild(script);
}
但是我现在尝试注入(inject) 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 -->
如何动态地将其注入(inject) <head>
?
更新:我最终使用了他们的 client-side solution .
最佳答案
如果你想添加一个带有 src 属性的脚本标签到 head 你应该使用
var script= document.createElement('script');
script.src = "SOME_URL";
document.head.appendChild(script);
注释文档。头部,而不是正文
如果你想添加一个包含一些脚本的脚本标签,请使用
var script= document.createElement('script');
脚本.text =“代码”;
document.head.appendChild(script);
如果您只需要在页面上运行此代码,您可以使用 eval("CODE");
其中 code 是不带脚本标签的 js 代码
也许this tool可以帮助逃脱
关于javascript - 动态地将脚本注入(inject)<head>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42490336/