<script async src="https://www.googletagmanager.com/gtag/js?id=<key here>"></script>
<script>
const container = document.getElementById('app');
const key = container.getAttribute('secret-key');
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', key);
</script>我正在尝试访问我需要在<script>标签中添加Google的密钥。我能够在第二个代码块中使用
const container = document.getElementById('app');
const key = container.getAttribute('secret-key');我想对第一个<script>子句使用相同的键,但我不确定是否可以对内联<script>执行相同的操作?我想使用相同的const key来替换<key here>。
我怎样才能做到这一点?
编辑
<script>
function appendGAScriptTag() {
const configKeys = JSON.parse(container.getAttribute('data-bootstrap')).common.conf;
const gaKey = configKeys['GOOGLE_ANALYTICS_KEY'];
let gaScriptTag = document.createElement('script');
gaScriptTag.type = 'text/javascript';
gaScriptTag.async = true;
gaScriptTag.src = `https://www.googletagmanager.com/gtag/js?id=${gaKey}`;
document.getElementsByTagName('head')[0].appendChild(gaScriptTag);
}
appendGAScriptTag(); // <--- calling it here
</script>发布于 2021-11-30 23:40:36
您可以使用.动态创建<script>标记。再来点JavaScript!
function appendGAScriptTag() {
var gaScriptTag = document.createElement('script');
gaScriptTag.type = 'text/javascript';
gaScriptTag.async = true;
gaScriptTag.src = `https://www.googletagmanager.com/gtag/js?id=${document.getElementById('app').getAttribute('secret-key')}`;
document.getElementsByTagName('head')[0].appendChild(gaScriptTag);
}
当您想将生成的元素注入DOM时,请在预先存在的JavaScript代码中调用JavaScript。
https://stackoverflow.com/questions/70177207
复制相似问题