You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将包含自定义变量的特殊script脚本插入到页面header中?

可行实现方案

有两种常用的实现方式,都可以保证脚本正确插入head且执行顺序符合要求:

方案1:分步创建脚本元素(更稳定)

这种方式分别创建配置脚本和外部加载脚本,按顺序插入head,可以完全控制脚本的属性和执行顺序,不会出现配置未定义的异常:

// 插入内联配置脚本
const configScript = document.createElement('script');
configScript.type = 'text/javascript';
configScript.textContent = `
var _iub = _iub || []; 
_iub.csConfiguration = {
    "countryDetection": true,
    "reloadOnConsent": true,
    "consentOnContinuedBrowsing": false,
    "perPurposeConsent": true,
    "purposes": "1,2,3,4,5",
    "lang": "en",
    "siteId": xxxx,
    "cookiePolicyId": 494xxxx,
    "cookiePolicyUrl": "https://www.iubenda.com/privacy-policy/xxxx",
    "banner": {
        "acceptButtonDisplay": true,
        "customizeButtonDisplay": true,
        "rejectButtonDisplay": true,
        "position": "float-bottom-center",
        "backgroundOverlay": true
    }
};
`;
document.head.appendChild(configScript);

// 插入外部加载脚本
const loaderScript = document.createElement('script');
loaderScript.type = 'text/javascript';
loaderScript.src = '//cdn.iubenda.com/cs/iubenda_cs.js';
loaderScript.charset = 'UTF-8';
loaderScript.async = true;
document.head.appendChild(loaderScript);

方案2:一次性插入HTML片段(更简洁)

如果希望代码更简短,可以直接通过insertAdjacentHTML方法把完整的脚本片段插入到head末尾,不会覆盖head内已有的内容:

document.head.insertAdjacentHTML('beforeend', `
<script type="text/javascript"> 
var _iub = _iub || []; 
_iub.csConfiguration = {"countryDetection":true,"reloadOnConsent":true,"consentOnContinuedBrowsing":false,"perPurposeConsent":true,"purposes":"1,2,3,4,5","lang":"en","siteId":xxxx,"cookiePolicyId":494xxxx,"cookiePolicyUrl":"https://www.iubenda.com/privacy-policy/xxxx", "banner":{ "acceptButtonDisplay":true,"customizeButtonDisplay":true,"rejectButtonDisplay":true,"position":"float-bottom-center","backgroundOverlay":true }}; 
</script> 
<script type="text/javascript" src="//cdn.iubenda.com/cs/iubenda_cs.js" charset="UTF-8" async></script>
`);

内容的提问来源于stack exchange,提问作者user16940297

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 15:06:00