我需要通过 Google 跟踪代码管理器中的自定义标记在
标签 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> 标记是字符串变量的一部分,但它仍会被解释。请参阅下面的屏幕截图。
我尝试使用适当的实体(即 > )转义小于和大于符号,但这也失败了。
最佳答案
您可以在使用 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 跟踪代码管理器 - 代码配置 - 在 <script> 中附加 <script> 内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59524277/