javascript - Google 跟踪代码管理器 - 代码配置 - 在 <script> 中附加 <script> 内容

标签 javascript jquery

我需要通过 Google 跟踪代码管理器中的自定义标记在 元素之前添加两个 <script> 标记:

<script src="https://cdn.jsdelivr.net/npm/cookieconsent@3/build/cookieconsent.min.js" data-cfasync="false"></script>

<script>window.cookieconsent.initialise({"palette":{"popup":{"background":"#000"},"button":{"background":"#f1d600"}}});</script>

因为我需要它们出现在 元素之前,所以我使用 jQuery 通过appendTo() 将这些值作为字符串附加:

<script>

var cookieConsentStyles = '<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/cookieconsent@3/build/cookieconsent.min.css" />';
var cookieConsentJS = '<script src="https://cdn.jsdelivr.net/npm/cookieconsent@3/build/cookieconsent.min.js" data-cfasync="false"></script>';
var cookieConsentInit = '<script>window.cookieconsent.initialise({"palette":{"popup":{"background":"#000"},"button":{"background":"#f1d600"}}});</script>';

jQuery(cookieConsentStyles).appendTo('head');
jQuery(cookieConsentJS).appendTo('body');
jQuery(cookieConsentInit).appendTo('body');
</script>

我已经确认这在浏览器控制台中有效,但在 Google 跟踪代码管理器中不起作用,因为任何 JS 代码都需要位于 <script> 标记之间。因此,尽管变量字符串中的 <script> 标记是字符串变量的一部分,但它仍会被解释。请参阅下面的屏幕截图。

enter image description here

我尝试使用适当的实体(即 > )转义小于和大于符号,但这也失败了。

最佳答案

您可以在使用 onload 事件加载父脚本时运行 cookie 同意脚本。这是一个例子:

var cookieConsentJS = document.createElement( 'script' );
cookieConsentJS.type = 'text/javascript';
cookieConsentJS.src = '/path/to/cookieconsent.min.js';
cookieConsentJS.setAttribute('data-cfasync', false); // not sure what this is, but not touching.

// this part of the code will run when the script is loaded. 
cookieConsentJS.onload = function() {
    // here is your code running outside of a string.
    window.cookieconsent.initialise({
        "palette":{
            "popup":{"background":"#000"},
            "button":{"background":"#f1d600"}
        }
    });
};

// now let's append your code to the body.
document.body.appendChild( cookieConsentJS );

请注意,在此上下文中未使用 jQuery。

关于javascript - Google 跟踪代码管理器 - 代码配置 - 在 &lt;script&gt; 中附加 &lt;script&gt; 内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59524277/

相关文章:

javascript - 中断包含 AJAX 类型函数的 for 循环

javascript - (jquery) 防止 div 在页面加载期间显示

javascript - 按数据在 highcharts 条形图中命名条形

json - groupon json 请求不起作用

javascript - 如何组合 .change(function() 两种不同类型的输入并将值发送到相同的函数参数

javascript - 无法检索全日历事件的时间和日期

javascript - 在 javascript 中将对象 (json) .json 保存在文件中

JavaScript 从匿名函数中读取私有(private)变量

javascript - 为什么这个javascript无限循环?

jquery - 将下拉菜单中对象的方向从垂直更改为水平?