How to insert special script into header?

Hi, I know how to insert a standard script to the body or header (changing .body or .header) depending on the case with:

document.body.appendChild(document.createElement('script')).src = 'https://url.com';

But I have a script that I need to insert into the header but it contains a var and I’m not sure how I should insert it.

<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>

Any ideas?
Thanks.

You can use the .textContent property of the script element to attach the body of your script. Example…

let script = document.createElement("script");
script.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(script);

Notice how we create the script element, then using .textContent you can set the body of that script tag, then append it where you need to. Now obviously make sure your code is properly escaped and using the correct single/double quotes so that you have a full string.

This should be all you need. Play with this and you should get something working in no time.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.